package cn.yunyichina.provider.pay.service.impl;

import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.framework.mvc.dao.BaseDao;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.framework.qiniu.QiniuService;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.base.*;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.finance.FinanceCollectVo;
import cn.yunyichina.provider.iface.entity.hisiface.finance.FinanceCollectVoResponse;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.pay.config.Alipay;
import cn.yunyichina.provider.pay.config.Config;
import cn.yunyichina.provider.pay.constant.MethodRouter;
import cn.yunyichina.provider.pay.dao.*;
import cn.yunyichina.provider.pay.entity.*;
import cn.yunyichina.provider.pay.service.*;
import cn.yunyichina.provider.pay.thread.CreateBillRunnable;
import cn.yunyichina.provider.pay.thread.HisPayfinanceRunnable;
import cn.yunyichina.provider.pay.thread.PaymentCheckRunnable;
import cn.yunyichina.provider.pay.utils.BigDecimalUtil;
import cn.yunyichina.provider.pay.vo.*;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IDUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * 对账平台后台业务接口 Created by Joezhou on 2016/10/26.
 */
@Service
public class FinanceServiceImpl implements FinanceService {

	@Autowired
	private PaymentCheckSourceFileDao paymentSourceFileDao;

	@Autowired
	private PaymentJournalDao paymentJournalDao;

	@Autowired
	private HisOrderCheckedErrorDao hisOrderCheckedErrorDao;

	@Autowired
	private HisOrderCheckedDao hisOrderCheckedDao;

	@Autowired
	private PaymentServiceImpl paymentService;

	@Autowired
	private HisOrderDao hisOrderDao;

	@Autowired
	private PlatformAccountDao platformAccountDao;

	@Resource
	private FinanceExcelService financeExcelService;

	@Autowired
	private PaymentSettingDao paymentSettingDao;

	@Resource
	private CheckPaymentService checkPaymentService;

	@Resource
	private ThirdFinanceService thirdFinanceService;

	@Resource
	private HisPayfinanceService hisPayfinanceService;

	private static Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);

	private static SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");

	private static SimpleDateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static SimpleDateFormat YYYYMMDDHHMISS14 = new SimpleDateFormat("yyyyMMddHHmmss");
	
	

	@Resource
	private Properties yaml;
	
	/**
	 * 事件定义
	 */
	private final static Map<String,String> eventDefineMap = new HashMap<>();
	static {
		eventDefineMap.put("CK_CHECK_SUCESSFUL","对账成功");
		eventDefineMap.put("CK_CLEAN_PLATFROM_DATA","清理-第三方收单机构与平台对账数据失败");
		eventDefineMap.put("CK_CLEAN_HIS_DATA","清理-HIS系统与平台对账数据失败");
		eventDefineMap.put("CK_PULL_PAY_BILL","对账-拉第三方收单机构订单流水失败");
		eventDefineMap.put("CK_PLATFORM_CHECK_PAY","对账-平台与第三方收单机构对账失败");
		eventDefineMap.put("CK_PULL_HIS_BILL","对账-拉HIS系统订单流水失败");
		eventDefineMap.put("CK_PLATFORM_CHECK_HIS","对账-平台与HIS对账失败");
	}

	/**
	 * 发送短信
	 * @param checkAccountSms
	 * @return
	 */
	public static ResponseObject sendSms(CheckAccountSms checkAccountSms) {
		try {
			ResponseObject resObj=new ResponseObject();
			logger.info("发送短信FinanceServiceImpl->sendSms请求:"+JSON.toJSONString(checkAccountSms));
			resObj=MessageService.sendSms(JsonUtils.toJsonString(checkAccountSms));
			logger.info("发送短信FinanceServiceImpl->sendSms返回:"+JSON.toJSONString(resObj));
			return resObj;
		} catch (Exception e) {
			logger.error("发送短信失败",e);
		}
		return null;
	}
	
	/**
	 * 发送对账异常短信<br>
	 * ${hospitalName}生成${date}（批次:${batch}）的对账数据时发生${level}错误， 错误是:${problemDescription}。请联系管理员人工排查原因。
	 * @return
	 */
	public static List<ResponseObject> sendSmsForFail(String orgId,String eventCode,String hospitalName,String date,String batch,String level,String problemDescription) {
		try {
			CheckAccountSms checkAccountSms = new CheckAccountSms();
			checkAccountSms.setSmsType(CheckAccountSms.MSG_TYPE_CHECK_ACCOUNT_FAIL);
			checkAccountSms.setDate(date);
			checkAccountSms.setBatch(batch);

			if(StringUtils.isNotBlank(level)){
				switch (level){
					case "2": level = "严重";
						break;
					case "3": level = "致命";
						break;
				}
			}

			checkAccountSms.setLevel(level);
			checkAccountSms.setProblemDescription(problemDescription);
			
			List<ResponseObject> listReturn = new ArrayList<>();
			
			if (StringUtils.isBlank(hospitalName)) {
				Map<String,Object> paramOrg = new HashMap<>();
			    paramOrg.put("id", orgId);
			    JSONObject jsonOrg = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.org.by.id.find", JsonUtils.toJsonString(paramOrg)).getResult());
			    if (jsonOrg != null) {
			    	hospitalName = jsonOrg.getString("org_name");
			    }
			    else {
			    	hospitalName = orgId;
			    }
				
			}
			checkAccountSms.setHospitalName(hospitalName);
			
			Map<String,Object> param = new HashMap<>();
			param.put("org_id", orgId);
			param.put("event_code", eventCode);
			logger.info("发送短信FinanceServiceImpl->sendSmsForFail->matchRemindSetting请求:"+JsonUtils.toJsonString(param));
			List<RemindSettingVo> listRemind = BaseService.getBaseClient().matchRemindSetting(JsonUtils.toJsonString(param));
			logger.info("发送短信FinanceServiceImpl->sendSmsForFail->matchRemindSetting返回:"+JsonUtils.toJsonString(listRemind));
			if (CollectionUtils.isNotEmpty(listRemind)) {
				for (RemindSettingVo remindSettingVo : listRemind) {
					checkAccountSms.setSmsMobile(remindSettingVo.getRemindUserMobile());
					listReturn.add(sendSms(checkAccountSms));
				}
			}
			
			
			return listReturn;
		} catch (Exception e) {
			logger.error("发送短信失败",e);
		}
		return null;
		
	}
	/**
	 * 发送对账成功短信<br>
	 * ${hospitalName}生成${date}（批次:${batch}）的对账数据正常，可进入系统进行查看
	 * @return
	 */
	public static List<ResponseObject> sendSmsForSuccess(String orgId,String eventCode,String hospitalName,String date,String batch,String diffCount ,String diffAmount) {
		try {
			CheckAccountSms checkAccountSms = new CheckAccountSms();
			checkAccountSms.setSmsType(CheckAccountSms.MSG_TYPE_CHECK_ACCOUNT_SUCCESS);
			checkAccountSms.setHospitalName(hospitalName);
			checkAccountSms.setDate(date);
			checkAccountSms.setBatch(batch);
			checkAccountSms.setDiffCount(diffCount);
			checkAccountSms.setDiffAmount(diffAmount);
			
			List<ResponseObject> listReturn = new ArrayList<>();
			
			Map<String,Object> param = new HashMap<>();
			param.put("org_id", orgId);
			param.put("event_code", eventCode);
			logger.info("发送短信FinanceServiceImpl->sendSmsForSuccess->matchRemindSetting请求:"+JsonUtils.toJsonString(param));
			List<RemindSettingVo> listRemind = BaseService.getBaseClient().matchRemindSetting(JsonUtils.toJsonString(param));
			logger.info("发送短信FinanceServiceImpl->sendSmsForSuccess->matchRemindSetting返回:"+JsonUtils.toJsonString(listRemind));
			if (CollectionUtils.isNotEmpty(listRemind)) {
				for (RemindSettingVo remindSettingVo : listRemind) {
					checkAccountSms.setSmsMobile(remindSettingVo.getRemindUserMobile());
					listReturn.add(sendSms(checkAccountSms));
				}
			}
			
			return listReturn;
		} catch (Exception e) {
			logger.error("发送短信失败",e);
		}
		return null;
	}
	
	public static void insertLog(String orgId,String eventCode,String content) {
		LogVo logVo = new LogVo();
		logVo.setOrgId(orgId);
		logVo.setEventCode(eventCode);
		logVo.setEventName(eventDefineMap.get(eventCode));
		logVo.setContent(content);
		insertLog(logVo);
		
	}
	/**
	 * 记录系统日志
	 * orgId必须输入
	 * @param log
	 */
	public static void insertLog(LogVo log) {
		try {
			JSONObject paramLog = JsonUtils.parseObject(thLogInfo.get());
			logger.info("FinanceServiceImpl->insertLog"+JsonUtils.toJsonString(paramLog));
			if (StringUtils.isBlank(log.getOrgId())) {
				throw new CallException("-2", "系统日志：orgId必须输入");
			}
			if (StringUtils.isBlank(log.getContent())) {
				log.setContent("无");
			}
			if (StringUtils.isBlank(log.getId())) {
				log.setId(IDUtils.getUUID32());
			}
			
			if (StringUtils.isBlank(log.getBeginOperatorTime())) {
				log.setBeginOperatorTime(YYYYMMDDHHMMSS.format(new Date()));
			}
			if (StringUtils.isBlank(log.getEndOperatorTime())) {
				log.setEndOperatorTime(log.getBeginOperatorTime());
			}
			if (StringUtils.isBlank(log.getBatchNo())) {
				
				if (paramLog != null) {
					log.setBatchNo(paramLog.getString("batch_no"));
				}
				else {
					log.setBatchNo("not_batch_no");
				}
//				log.setBatchNo(YYYYMMDDHHMISS14.format(new Date()));
			}
			
			if (StringUtils.isBlank(log.getEventCode())) {
				log.setEventCode("finance");
			}
			if (StringUtils.isBlank(log.getEventName())) {
				log.setEventName(eventDefineMap.get(log.getEventCode()));
			}
			if (StringUtils.isBlank(log.getModuleCode())) {
				log.setModuleCode("CHECK_ACCOUNT");
			}
			
			if (log.getLevel() == null) {
				Map<String,Object> paramEvent = new HashMap<>();
	        	paramEvent.put("event_code", log.getEventCode());
	        	paramEvent.put("module_code", "CHECK_ACCOUNT");
	        	Response responseEvent = BaseService.callHumpFromInternal("yyt.base.event.get", JsonUtils.toJsonString(paramEvent));
	        	if (StringUtils.isNotBlank(responseEvent.getResult())) {
	        		EventVo event = JsonUtils.parseObject(responseEvent.getResult(), EventVo.class);
	        		log.setLevel(event.getEventLevel().shortValue());
	        	}
	        	else {
	        		log.setLevel((short) 1 );	
	        	}
				
			}
			
			if (StringUtils.isBlank(log.getModuleName())) {
				log.setModuleName("对账系统");
			}
			if (StringUtils.isBlank(log.getOperatorBy())) {
				if (paramLog != null) {
					log.setOperatorBy(paramLog.getString("operator_by"));
				}
				else {
					log.setOperatorBy("not_operator_by");
				}
//				log.setOperatorBy("system");

			}
			if (StringUtils.isBlank(log.getOperatorName())) {
				if (paramLog != null) {
					log.setOperatorName(paramLog.getString("operator_name"));
				}
				else {
					log.setOperatorName("not_operator_name");
				}
//				log.setOperatorName("system");

			}
			if (StringUtils.isBlank(log.getOperatorTime())) {
				log.setOperatorTime(YYYYMMDDHHMMSS.format(new Date()));

			}
			if (StringUtils.isBlank(log.getOrgCode())) {
				log.setOrgCode("orgId:"+log.getOrgId());

			}
			if (StringUtils.isBlank(log.getOrgName())) {
				Map<String,Object> paramOrg = new HashMap<>();
	            paramOrg.put("id", log.getOrgId());
	            JSONObject jsonOrg = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.org.by.id.find", JsonUtils.toJsonString(paramOrg)).getResult());
	            if (jsonOrg != null) {
	            	log.setOrgName(jsonOrg.getString("org_name"));
	            	log.setOrgCode(jsonOrg.getString("org_code"));
	            }
				
			}
			BaseService.callHumpFromInternal("yyt.base.log.insert", JsonUtils.toJsonString(log));
		} catch (Exception e) {
			logger.error("记录系统日志失败:"+JsonUtils.toJsonString(log));
		}
    }


	/**
	 * 参数非空验证
	 * 
	 * @param param
	 * @param fieldNames
	 */
	private void validParam(JSONObject param, String fieldNames) {
		if (StringUtils.isNotBlank(fieldNames)) {
			String[] arrFieldName = fieldNames.split(",");
			for (String fieldName : arrFieldName) {
				if (StringUtils.isBlank(param.getString(fieldName.trim()))) {
					logger.error("参数异常" + fieldName.trim());
					throw new CallException(ErrorCodeDefine.MESSAGE_PARAM, "参数异常" + fieldName.trim());
				}
			} 
		}
	}

	/**
	 * 人民币，单位分转换为元
	 * 
	 * @param amount
	 * @return 如果amount为null返回空格；如果为0，返回0.00
	 */
	public static String transformRMB(Integer amount) {
		if (amount == null) {
			return " ";
		} else if (amount == 0) {
			return "0.00";
		}
		BigDecimal b = new BigDecimal(amount);
		return b.divide(new BigDecimal(100)).toString();
	}

	/**
	 * 对账总览
	 *
	 * @param strJson
	 * @return org_id,begin_pay_date,end_pay_date
	 * @interfacename yyt.pay.finance.summary.timeperiod.query
	 */
	@Override
	public List<Map<String, Object>> queryFinanceSummaryTimeperiod(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);
		String orgId = param.getString("org_id");

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		List<Map<String, Object>> listReturn = new ArrayList<>();

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return listReturn;
		}

		Calendar cStart = Calendar.getInstance();
		cStart.setTime(DateUtils.StringToDate(beginPayDate));

		Calendar cEnd = Calendar.getInstance();
		cEnd.setTime(DateUtils.StringToDate(endPayDate));

		// 间隔天数
		int days = Math.abs(DateUtils.getDaysBetween(cEnd, cStart)) + 1;

		logger.info("days=" + days);

		// 查询org下平台信息
		try {
			int hisReceiveAmountAll = 0;
			int platformReceiveAmountAll = 0;
			int differenceAmountAll = 0;
			int differenceNumberAll = 0;
			for (int i = 0; i < days; i++) {

				int hisReceiveAmountOneDay = 0;
				int platformReceiveAmountOneDay = 0;
				int differenceAmountOneDay = 0;
				int differenceNumberOneDay = 0;

				beginPayDate = YYYYMMDD.format(cEnd.getTime()) + " 00:00:00";
				endPayDate = YYYYMMDD.format(cEnd.getTime()) + " 23:59:59";

				Map<String, Object> mapOneDay = new LinkedHashMap();
				mapOneDay.put("pay_date", YYYYMMDD.format(cEnd.getTime()));

				PlatformAccount platformAccount = new PlatformAccount();
				platformAccount.setOrgId(orgId);
				if (StringUtils.isNotBlank(param.getString("platform_id"))) {
					platformAccount.setPlatformId(param.getString("platform_id"));
				}
				List<PlatformAccount> platformAccounts = platformAccountDao.select(platformAccount);
				logger.info("platformAccounts-size=" + platformAccounts.size());

				List<Map> listPlatform = new ArrayList<>();
				mapOneDay.put("records", listPlatform);
				
				

				Map<String, List<JSONObject>> existPlatformMap = new HashMap<>();
				
				for (PlatformAccount account : platformAccounts) {
					JSONObject accountJsonOne = JsonUtils.parseObject(account);
					if (!existPlatformMap.containsKey(account.getPlatformId())) {
						
						Map<String, Object> mapPlatformOne = new HashMap<>();
						mapPlatformOne.put("platform_id", account.getPlatformId());
						mapPlatformOne.put("platform_name", account.getPlatformName());
						List<JSONObject> listAccountOfOnePlatform = new ArrayList<>();
						listAccountOfOnePlatform.add(accountJsonOne);
						mapPlatformOne.put("accounts", listAccountOfOnePlatform);
						listPlatform.add(mapPlatformOne);

						existPlatformMap.put(account.getPlatformId(), listAccountOfOnePlatform);
					} else {
						List<JSONObject> listAccountOfOnePlatform = existPlatformMap.get(account.getPlatformId());
						listAccountOfOnePlatform.add(accountJsonOne);
					}

					HisOrder sumHisOrder = hisOrderDao.queryFinanceSummaryOneday(beginPayDate, endPayDate,
							account.getPayAppId(), account.getPlatformId(), orgId);

					accountJsonOne.put("pay_app_name", account.getPlatformName());
					accountJsonOne.put("his_receive_amount", "0");
					accountJsonOne.put("platform_receive_amount", "0");
					accountJsonOne.put("difference_amount", "0");
					accountJsonOne.put("difference_number", "0");
					if (sumHisOrder != null) {
						// 医院应收金额
						accountJsonOne.put("his_receive_amount", sumHisOrder.getPayAmount());
						hisReceiveAmountAll += getNotZeroInteger(sumHisOrder.getPayAmount());
						hisReceiveAmountOneDay += getNotZeroInteger(sumHisOrder.getPayAmount());
					}

					PaymentJournal sumPaymentJournal = paymentJournalDao.queryFinanceSummaryOneday(beginPayDate,
							endPayDate, account.getPayAppId(), account.getPlatformId(), orgId);
					if (sumPaymentJournal != null) {
						// 平台实收金额
						accountJsonOne.put("platform_receive_amount", sumPaymentJournal.getPayAmount());
						platformReceiveAmountAll += getNotZeroInteger(sumPaymentJournal.getPayAmount());
						platformReceiveAmountOneDay += getNotZeroInteger(sumPaymentJournal.getPayAmount());
					}

					HisOrderCheckedError sumHisOrderCheckedError = hisOrderCheckedErrorDao.queryFinanceSummaryOneday(
							beginPayDate, endPayDate, account.getPayAppId(), account.getPlatformId(), orgId);
					if (sumHisOrderCheckedError != null) {

						// 差错金额
						accountJsonOne.put("difference_amount", sumHisOrderCheckedError.getYytPayAmount() == null ? 0 : sumHisOrderCheckedError.getYytPayAmount());

						// 差错笔数
						accountJsonOne.put("difference_number", sumHisOrderCheckedError.getYytTotalAmount() );

						differenceAmountAll += getNotZeroInteger(sumHisOrderCheckedError.getYytPayAmount());
						differenceNumberAll += getNotZeroInteger(sumHisOrderCheckedError.getYytTotalAmount());
						differenceAmountOneDay += getNotZeroInteger(sumHisOrderCheckedError.getYytPayAmount());
						differenceNumberOneDay += getNotZeroInteger(sumHisOrderCheckedError.getYytTotalAmount());
					}

				}
				
				if ( ! "1".equals(param.getString("not_union_pay_id_flag"))) {
					Iterator<List<JSONObject>> it = existPlatformMap.values().iterator();
					while (it.hasNext()) {
						List<JSONObject> listTmp = it.next();
						JSONObject accountJsonOne = listTmp.get(0);
						if (listTmp.size() > 1) {
							//执行合并
							int size = listTmp.size();
							for (int k=1;k<size;k++) {
								JSONObject accountJsonOneNext = listTmp.get(k);
								accountJsonOne.put("his_receive_amount", accountJsonOne.getInteger("his_receive_amount")+accountJsonOneNext.getInteger("his_receive_amount"));
								accountJsonOne.put("platform_receive_amount", accountJsonOne.getInteger("platform_receive_amount")+accountJsonOneNext.getInteger("platform_receive_amount"));
								accountJsonOne.put("difference_amount", accountJsonOne.getInteger("difference_amount")+accountJsonOneNext.getInteger("difference_amount"));
								accountJsonOne.put("difference_number", accountJsonOne.getInteger("difference_number")+accountJsonOneNext.getInteger("difference_number"));
							}
							listTmp.clear();
							listTmp.add(accountJsonOne);
						}
						accountJsonOne.put("difference_number", accountJsonOne.getInteger("difference_number"));
					}
				}
				else {
					Iterator<List<JSONObject>> it = existPlatformMap.values().iterator();
					while (it.hasNext()) {
						List<JSONObject> listTmp = it.next();
						int size = listTmp.size();
						for (int k=0;k<size;k++) {
							JSONObject accountJsonOne = listTmp.get(k);
							accountJsonOne.put("difference_number", accountJsonOne.getInteger("difference_number"));
						}
						
					}
				}
				
				
				Map<String, Object> recordSum = new LinkedHashMap<>();

				recordSum.put("his_receive_amount", hisReceiveAmountOneDay);
				recordSum.put("platform_receive_amount", platformReceiveAmountOneDay);
				recordSum.put("difference_amount", platformReceiveAmountOneDay-hisReceiveAmountOneDay);
				recordSum.put("difference_number", differenceNumberOneDay);

				mapOneDay.put("record_sum", recordSum);

				listReturn.add(mapOneDay);

				cEnd.add(Calendar.DATE, -1);

			} // for

			// 单日统计不需要执行总体统计
			if (!param.containsKey("not_sum_all_flag")) {
				Map<String, Object> recordSumAll = new LinkedHashMap<>();
				recordSumAll.put("his_receive_amount", hisReceiveAmountAll);
				recordSumAll.put("platform_receive_amount", platformReceiveAmountAll);
				recordSumAll.put("difference_amount", differenceAmountAll);
				recordSumAll.put("difference_number", differenceNumberAll);
				listReturn.add(recordSumAll);
			}

			logger.debug(JsonUtils.toJsonString(listReturn));
			logger.info("queryFinanceSummaryTimeperiod end");

			return listReturn;

		} catch (Exception e) {
			logger.error("对账总览异常:" + strJson, e);
			listReturn = new ArrayList();
			// throw new CallException("-1", "统计异常");
		}

		return listReturn;
	}

	private static int getNotZeroInteger(Object amount) {
		if (amount == null) {
			return 0;
		}
		if (amount instanceof Integer) {
			return (Integer) amount;
		}
		return Integer.parseInt(amount.toString());
	}

	/**
	 * 对账总览-资金账户详情（单日）
	 *
	 * @param strJson
	 * @return org_id,pay_date
	 * @interfacename yyt.pay.finance.summary.oneday.query
	 */
	public Map<String, Object> queryFinanceSummaryOneday(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "org_id,pay_date");
		param.put("begin_pay_date", param.getString("pay_date"));
		param.put("end_pay_date", param.getString("pay_date"));
		param.put("not_sum_all_flag", "1");// 避免总体统计
		param.put("not_union_pay_id_flag", "1");
		List<Map<String, Object>> list = this.queryFinanceSummaryTimeperiod(JsonUtils.toJsonString(param));
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 对账总览-资金账户详情（单平台）
	 *
	 * @param strJson
	 *            org_id,pay_date,platform_id
	 * @return
	 * @interfacename yyt.pay.finance.summary.platform.query
	 */
	public Map<String, Object> queryFinanceSummaryPlatform(String strJson) {
		logger.info(strJson);

		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "org_id,pay_date,platform_id");
		param.put("begin_pay_date", param.getString("pay_date"));
		param.put("end_pay_date", param.getString("pay_date"));
		param.put("not_sum_all_flag", "1");// 避免总体统计
		param.put("not_union_pay_id_flag", "1");
		List<Map<String, Object>> list = this.queryFinanceSummaryTimeperiod(JsonUtils.toJsonString(param));
		if (CollectionUtils.isNotEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 通用解析-组装类型的列表查询
	 * 
	 * @param strJson
	 * @param clz
	 * @param dao
	 * @return
	 */
	public <T> List<T> listEntity(String strJson, Class<T> clz, BaseDao<T> dao) {
		logger.debug("listEntity入参:" + strJson);
		JSONObject jsonObj = JsonUtils.parseObject(strJson);
		T entity = JsonUtils.parseObject(strJson, clz);

		PageInfo pageInfo = null;
		if (jsonObj.containsKey("page_info")) {
			pageInfo = JsonUtils.parseObject(jsonObj.getJSONObject("page_info"), PageInfo.class);
		} else {
			pageInfo = new PageInfo();
			if (StringUtils.isNotBlank(jsonObj.getString("page_size"))) {
				pageInfo.setPageSize(jsonObj.getIntValue("page_size"));
			}
			
			if (StringUtils.isNotBlank(jsonObj.getString("page_num"))) {
				pageInfo.setPageNum(jsonObj.getIntValue("page_num"));
			}
		}
		List<String> orderColumns = null;
		if (jsonObj.containsKey("orderColumns") && StringUtils.isNotEmpty(jsonObj.getString("orderColumns"))) {
			orderColumns = new ArrayList<String>();
			String str = jsonObj.getString("orderColumns");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0, str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				orderColumns.add((String) field);
			}
		}

		List<String> selects = null;
		if (jsonObj.containsKey("selects") && StringUtils.isNotEmpty(jsonObj.getString("selects"))) {
			selects = new ArrayList<String>();
			String str = jsonObj.getString("selects");
			if (str.startsWith("[")) {
				str = str.substring(1);
			}
			if (str.endsWith("]")) {
				str = str.substring(0, str.length() - 1);
			}
			String[] listObj = str.split(",");
			for (Object field : listObj) {
				selects.add((String) field);
			}
		}

		boolean isAsc = true;
		if (jsonObj.containsKey("isAsc")) {
			isAsc = jsonObj.getBooleanValue("isAsc");
		}

		List<T> list = dao.select(entity, selects, orderColumns, isAsc, pageInfo);

		logger.debug("listEntity：" + JsonUtils.toJsonString(list));

		return list;

	}

	/**
	 * 对账差错 <br>
	 * yyt.pay.finance.summary.difference.query
	 * 
	 * @param strJson
	 * @return
	 */
	public Map<String, Object> queryFinanceSummaryDifference(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		Map<String, Object> mapReturn = new HashMap<String, Object>();

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return mapReturn;
		}

		try {
			HisOrderCheckedError hisError = JsonUtils.parseObject(strJson, HisOrderCheckedError.class);
			hisError.setOrgId(param.getString("org_id"));

			hisError.setBeginYytPayTime(beginPayDate + " 00:00:00");
			hisError.setEndYytPayTime(endPayDate + " 23:59:59");

			param.putAll(JsonUtils.parseObject(hisError));
			
			param.put("orderColumns", "yyt_order_no");
			
			HisOrderCheckedError hisErrorSum = hisOrderCheckedErrorDao.selectCountAndAmount(hisError);
			Integer totalCount = hisErrorSum.getHisTotalAmount();

			String pageNum = param.getString("page_num");
			if(StringUtils.isNotBlank(pageNum)){
				PageInfo pageInfo = initPageInfo(param);
				doPageInfo(pageInfo, totalCount.longValue());
				mapReturn.put("page_info", pageInfo);
			}

			List<HisOrderCheckedError> listError = this.listEntity(JsonUtils.toJsonString(param),
					HisOrderCheckedError.class, hisOrderCheckedErrorDao);
			mapReturn.put("records", listError);


			mapReturn.put("his_total_receive_amount", 0);
			mapReturn.put("platform_total_receive_amount", 0);
			mapReturn.put("difference_number", 0);
			mapReturn.put("difference_amount", 0);

			if (CollectionUtils.isNotEmpty(listError)) {
//				int hisTotalReceiveAmountSum = 0;
//				int platformTotalReceiveAmountSum = 0;
//
//				for (HisOrderCheckedError error : listError) {
//					hisTotalReceiveAmountSum += getNotZeroInteger(error.getHisPayAmount());
//					platformTotalReceiveAmountSum += getNotZeroInteger(error.getYytPayAmount());
//
//				}
				mapReturn.put("his_total_receive_amount", hisErrorSum.getHisPayAmount());
				mapReturn.put("platform_total_receive_amount", hisErrorSum.getYytPayAmount());
				mapReturn.put("difference_number", hisErrorSum.getHisTotalAmount());
				mapReturn.put("difference_amount", (hisErrorSum.getYytPayAmount() == null ? 0 : hisErrorSum.getYytPayAmount())- (hisErrorSum.getHisPayAmount() == null ? 0 : hisErrorSum.getHisPayAmount()) );

			}

		} catch (Exception e) {
			logger.error("对账差错异常:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}
	
	/**
	 * 初始化分页信息
	 * @param param
	 * @return
	 */
	public static PageInfo initPageInfo(JSONObject param) {
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNum(1);
		pageInfo.setPageSize(10);
		if (StringUtils.isNotBlank(param.getString("page_num"))) {
			pageInfo.setPageNum(param.getInteger("page_num"));
		}
		if (StringUtils.isNotBlank(param.getString("page_size"))) {
			pageInfo.setPageSize(param.getInteger("page_size"));
		}
		param.put("pageInfo", pageInfo);
		return pageInfo;
		
	}
	
	/**
	 * 处理分页
	 * @param pageInfo
	 * @param totalCount 总记录数
	 */
	public static void doPageInfo(final PageInfo pageInfo,Long totalCount) {
		pageInfo.setTotal(totalCount);
		if (pageInfo.getPageNum()  == null) {
			pageInfo.setPageNum(1);
			
		}
		if (pageInfo.getPageSize()  == null) {
			pageInfo.setPageSize(10);
			
		}
		if (totalCount > 0) {
			int pageCount = (int) (totalCount/pageInfo.getPageSize());
			if (totalCount % pageInfo.getPageSize() != 0) {
				pageCount++;
			}
			pageInfo.setPages(pageCount);
		}
		else {
			pageInfo.setTotal(0L);
			pageInfo.setPages(0);
		}
	}

	/**
	 * 对账总览-对账详情 <br>
	 * yyt.pay.finance.records.query
	 * 
	 * @param strJson
	 * @return
	 */
	@Override
	public Map<String, Object> queryFinanceRecords(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		Map<String, Object> mapReturn = new HashMap<String, Object>();

		// 数据初始化
		mapReturn.put("his_total_receive_amount", "0");
		mapReturn.put("platform_total_receive_amount", "0");
		mapReturn.put("difference_number", 0);
		mapReturn.put("difference_amount", "0");
		mapReturn.put("records", ListUtils.EMPTY_LIST);

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return mapReturn;
		}

		List<FinanceRecordsVo> listChecked = null;
		try {
			HisOrderChecked hisOrderChecked = JsonUtils.parseObject(strJson, HisOrderChecked.class);
			hisOrderChecked.setOrgId(param.getString("org_id"));

			hisOrderChecked.setBeginYytPayTime(beginPayDate + " 00:00:00");
			hisOrderChecked.setEndYytPayTime(endPayDate + " 23:59:59");

			param.putAll(JsonUtils.parseObject(hisOrderChecked));

			Long totalCount = 0L;
			Map<String,Object> mapCount = hisOrderCheckedDao.queryRecordsCount(hisOrderChecked);
			if (mapCount != null) {
				if (mapCount.get("difference_number") != null) {
					totalCount = Long.parseLong(mapCount.get("difference_number").toString());
				}

				String pageNum = param.getString("page_num");
				if (totalCount > 0 && StringUtils.isNotBlank(pageNum)) {
					PageInfo pageInfo = initPageInfo(param);
					doPageInfo(pageInfo, totalCount);
					listChecked = hisOrderCheckedDao.queryRecords(hisOrderChecked, pageInfo);
					mapReturn.put("page_info", pageInfo);
				}else{
					listChecked = hisOrderCheckedDao.queryRecords(hisOrderChecked, null);
				}
				mapReturn.putAll(mapCount);
			}
			else {
				logger.error("查询总数错误,总数为null");
			}
			mapReturn.put("records", listChecked);

		} catch (Exception e) {
			logger.error("对账总览-对账详情:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}

	/**
	 * 对账总览-订单流水详情 <br>
	 * yyt.pay.finance.records.detail.query
	 * 
	 * @param strJson
	 *            yyt_order_no
	 * @return
	 */
	public Map<String, Object> queryFinanceRecordsDetail(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "yyt_order_no");

		Map<String, Object> mapReturn = new HashMap<String, Object>();

		try {
			
			OrderExtVo order = BaseService.getBaseClient().getOrderByOrderNo(param.getString("yyt_order_no"));
			if (order != null) {
				mapReturn.putAll(JsonUtils.parseObject(order));
			} else {
				logger.error("订单不存在：" + strJson);
			}

			HisOrderChecked hisOrderChecked = new HisOrderChecked();
			hisOrderChecked.setYytOrderNo(param.getString("yyt_order_no"));
			hisOrderChecked.setPayStatus(param.getShort("pay_status"));
			List<HisOrderChecked> listChecked = hisOrderCheckedDao.select(hisOrderChecked);
			if (CollectionUtils.isNotEmpty(listChecked)) {
				if (listChecked.size() == 1) {
					mapReturn.putAll(JsonUtils.parseObject(listChecked.get(0)));
					
				}
				else if (listChecked.size() == 2) {
					HisOrderChecked checked = listChecked.get(0);
					if (checked.getPayStatus() == 1) {
						mapReturn.putAll(JsonUtils.parseObject(checked));
						HisOrderChecked checkedRefund = listChecked.get(1);
						mapReturn.put("refund_payment_deal_id", checkedRefund.getPaymentDealId());
					}
					else {
						mapReturn.putAll(JsonUtils.parseObject(listChecked.get(1)));
						mapReturn.put("refund_payment_deal_id", checked.getPaymentDealId());
					}
				}
				mapReturn.put("his_pay_amount", mapReturn.get("pay_amount"));
				mapReturn.put("his_insurance_amount", mapReturn.get("insurance_amount"));
				mapReturn.put("his_total_amount", mapReturn.get("total_amount"));
				
				mapReturn.put("yyt_pay_amount", mapReturn.get("pay_amount"));
				mapReturn.put("yyt_insurance_amount", mapReturn.get("insurance_amount"));
				mapReturn.put("yyt_total_amount", mapReturn.get("total_amount"));
				
				mapReturn.put("checked_flag", true);
				mapReturn.put("check_status", 1);
			} else {
				mapReturn.put("checked_flag", false);
				HisOrderCheckedError hisError = new HisOrderCheckedError();
				hisError.setYytOrderNo(param.getString("yyt_order_no"));
				hisError.setPayStatus(param.getShort("pay_status"));
				List<HisOrderCheckedError> listError = hisOrderCheckedErrorDao.select(hisError);

				if (CollectionUtils.isNotEmpty(listError)) {
					mapReturn.putAll(JsonUtils.parseObject(listError.get(0)));

				} else {// 没有对账
					mapReturn.put("not_checked", true);
				}

			}
			
			if (order != null) {
				mapReturn.put("pay_mode",order.getPayMode());
			} else {
				logger.error("订单不存在：" + strJson);
			}

		} catch (Exception e) {
			logger.error("对账总览-订单流水详情:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}

	/**
	 * 流水明细及统计-医院订单流水明细 <br>
	 * yyt.pay.finance.details.hisdetails.query
	 * 
	 * @param strJson
	 *            yyt_order_no
	 * @return
	 */
	public Map<String, Object> queryFinanceDetailsHisdetails(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		Map<String, Object> mapReturn = new HashMap<String, Object>();
		mapReturn.put("records", ListUtils.EMPTY_LIST);

		mapReturn.put("his_total_receive_amount", "0");

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return mapReturn;
		}

		try {
			HisOrder hisOrder = JsonUtils.parseObject(strJson, HisOrder.class);
			hisOrder.setOrgId(param.getString("org_id"));

			hisOrder.setBeginPayTime(beginPayDate + " 00:00:00");
			hisOrder.setEndPayTime(endPayDate + " 23:59:59");

			param.putAll(JsonUtils.parseObject(hisOrder));

			Long totalCount = 0L;
			Map<String,Object> mapCount =  hisOrderDao.selectStat(hisOrder);
			if (mapCount != null) {
				if (mapCount.get("cnt") != null) {
					totalCount = Long.parseLong(mapCount.get("cnt").toString());
				}

				String pageNum = param.getString("page_num");

				if (totalCount > 0 && StringUtils.isNotBlank(pageNum)) {
					PageInfo pageInfo = initPageInfo(param);
					mapReturn.put("page_info", pageInfo);
					doPageInfo(pageInfo, totalCount);
				}

				List<HisOrder> listHisOrder = this.listEntity(JsonUtils.toJsonString(param), HisOrder.class,
						hisOrderDao);
				mapReturn.put("records", listHisOrder);
				mapReturn.putAll(mapCount);

			}
		} catch (Exception e) {
			logger.error("流水明细及统计-医院订单流水明细:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}

	/**
	 * 流水明细及统计-平台订单流水明细 <br>
	 * yyt.pay.finance.details.patdetails.query
	 * 
	 * @param strJson
	 *            yyt_order_no
	 * @return
	 */
	public Map<String, Object> queryFinanceDetailsPatdetails(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);
		if (StringUtils.isNotBlank(param.getString("yyt_order_no"))) {
			param.put("order_no", param.getString("yyt_order_no"));
		}

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		Map<String, Object> mapReturn = new HashMap<String, Object>();
		mapReturn.put("records", ListUtils.EMPTY_LIST);

		mapReturn.put("platform_total_receive_amount", "0");

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return mapReturn;
		}

		try {
			PaymentJournal paymentJournal = JsonUtils.parseObject(param, PaymentJournal.class);
			paymentJournal.setOrgId(param.getString("org_id"));

			paymentJournal.setBeginPayTime(beginPayDate + " 00:00:00");
			paymentJournal.setEndPayTime(endPayDate + " 23:59:59");

			param.putAll(JsonUtils.parseObject(paymentJournal));
			
			Long totalCount = 0L;
			Map<String,Object> mapCount =  paymentJournalDao.selectStat(paymentJournal);
			if (mapCount != null) {
				if (mapCount.get("cnt") != null) {
					totalCount = Long.parseLong(mapCount.get("cnt").toString());
				}

				PageInfo pageInfo = initPageInfo(param);
				List<String> orderColumns = null;
				if (param.containsKey("orderColumns") && StringUtils.isNotEmpty(param.getString("orderColumns"))) {
					orderColumns = new ArrayList<String>();
					String str = param.getString("orderColumns");
					if (str.startsWith("[")) {
						str = str.substring(1);
					}
					if (str.endsWith("]")) {
						str = str.substring(0, str.length() - 1);
					}
					String[] listObj = str.split(",");
					for (Object field : listObj) {
						orderColumns.add((String) field);
					}
				}
				else {
					orderColumns = new ArrayList<>();
					orderColumns.add("pay_time");
				}

				String pageNum = param.getString("page_num");
				List<Map> listPaymentJournal = null;
				if (totalCount > 0  && StringUtils.isNotBlank(pageNum)) {
					doPageInfo(pageInfo, totalCount);
					mapReturn.put("page_info", pageInfo);
					listPaymentJournal = paymentJournalDao.selectPatdetails(paymentJournal, null, orderColumns, true, pageInfo);
					//				List<PaymentJournal> listPaymentJournal = this.listEntity(JsonUtils.toJsonString(param),PaymentJournal.class, paymentJournalDao);
				}else{
					listPaymentJournal = paymentJournalDao.selectPatdetails(paymentJournal, null, orderColumns, true, null);
				}
				mapReturn.put("records", listPaymentJournal);
				mapReturn.putAll(mapCount);
			}

		} catch (Exception e) {
			logger.error("流水明细及统计-平台订单流水明细:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}

	/**
	 * ##### 流水明细及统计-平台订单流水统计
	 *
	 * @param datas
	 * @return
	 * @interfacename:yyt.pay.finance.details.patstatistics.query
	 */
	@Override
	public ResponseObject queryFinanceDetailsPatstatistics(String datas) {

		ResponseObject response = new ResponseObject();
		logger.info("queryFinanceDetailsPatstatistics, request data=" + datas);
		PatstatisticsVo request = JsonUtils.parseObject(datas, PatstatisticsVo.class);

		try {
			Validator.getInstance().validate(request);
		} catch (ValidateException ex) {
			logger.error("queryFinanceDetailsPatstatistics 数据校验失败:" + ex.getMessage() + "|入参:" + datas + "！");
			response.setResultCodeAndMessage("13", "数据校验失败:" + ex.getMessage() + "！");
			return response;
		}

		ArrayList<Patstatistics> pasts = new ArrayList<Patstatistics>();
		ArrayList<String> platformIds = new ArrayList<String>();

		// 查询org下平台信息
		try {
			PlatformAccount platformAccount = new PlatformAccount();
			platformAccount.setOrgId(request.getOrgId());
			List<PlatformAccount> platformAccounts = platformAccountDao.selectGroupByPlatformId(platformAccount);
			
			for (PlatformAccount account : platformAccounts) {
				platformIds.add(account.getPlatformId());
			}

			List<Date> betweenTwoDate = DateUtils.getDatesBetweenTwoDate(YYYYMMDD.parse(request.getBeginPayDate()),
					YYYYMMDD.parse(request.getEndPayDate()));

			String beginTime = request.getBeginPayDate() + " 00:00:00";
			String endTime = request.getEndPayDate() + " 23:59:59";
			List<PaymentJournal> journals = paymentJournalDao.selectDetailsPatstatistics(beginTime, endTime,
					request.getOrgId(), platformIds);
			logger.info("aaabbb"+journals.size());
			
			int sizeDate = betweenTwoDate.size();
			// 根据时间区分
			for (int i = sizeDate-1;i>=0;i--) {
				Date date = betweenTwoDate.get(i);
	
				Patstatistics pat = new Patstatistics();
				pat.setPay_date(YYYYMMDD.format(date));

				ArrayList<BillDetail> bills = new ArrayList<BillDetail>();

				for (PlatformAccount account : platformAccounts) {
					int totalAmount = 0;
					int insAmount = 0;
					int realAmount = 0;
					int totalCount = 0;
					int regAmount = 0;
					int regInsAmount = 0;
					int regRealAmount = 0;
					int regCount = 0;
					int mzAmount = 0;
					int mzInsAmount = 0;
					int mzRealAmount = 0;
					int mzCount = 0;
					int zyAmount = 0;
					int zyInsAmount = 0;
					int zyRealAmount = 0;
					int zyCount = 0;

					List<PaymentJournal> platA = new ArrayList<>();
					for (PaymentJournal journal : journals) {
						String parseDate = DateUtils.getDateStr(YYYYMMDD.parse(journal.getPayTime()));
						if (journal.getPlatformId().equals(account.getPlatformId())
								&& parseDate.equals(YYYYMMDD.format(date))) {
							platA.add(journal);
						}
					}

					for (PaymentJournal journal : platA) {
						Date joDate = YYYYMMDD.parse(journal.getPayTime());
						if (joDate.getTime() == date.getTime()) {
							if (journal.getPayStatus() == 2 || journal.getPayStatus() == 3
									|| journal.getPayStatus() == 5) { // 负交易变负数
								journal.setTotalAmount(journal.getTotalAmount() * -1);
								journal.setInsuranceAmount(journal.getInsuranceAmount() * -1);
								journal.setPayAmount(journal.getPayAmount() * -1);
							}
							
							totalCount++;
							
							totalAmount = totalAmount + journal.getTotalAmount();
							insAmount = insAmount + journal.getInsuranceAmount();
							realAmount = realAmount + journal.getPayAmount();

							if (journal.getOrderType() == 1) { // 挂号信息
								regAmount = regAmount + journal.getTotalAmount();
								regInsAmount = regInsAmount + journal.getInsuranceAmount();
								regRealAmount = regRealAmount + journal.getPayAmount();
								if (journal.getPayStatus() == 1 || journal.getPayStatus() == 4 || journal.getPayStatus() == 2 || journal.getPayStatus() == 5) {
									regCount++;
								}
							} else if (journal.getOrderType() == 3) { // 门诊信息
								mzAmount = mzAmount + journal.getTotalAmount();
								mzInsAmount = mzInsAmount + journal.getInsuranceAmount();
								mzRealAmount = mzRealAmount + journal.getPayAmount();
								if (journal.getPayStatus() == 1 || journal.getPayStatus() == 4 || journal.getPayStatus() == 2 || journal.getPayStatus() == 5) {
									mzCount++;
								}
							} else if (journal.getOrderType() == 4) { // 住院信息
								zyAmount = zyAmount + journal.getTotalAmount();
								zyInsAmount = zyInsAmount + journal.getInsuranceAmount();
								zyRealAmount = zyRealAmount + journal.getPayAmount();
								if (journal.getPayStatus() == 1 || journal.getPayStatus() == 4 || journal.getPayStatus() == 2 || journal.getPayStatus() == 5) {
									zyCount++;
								}
							}
						}
					}

					BillDetail details = new BillDetail();
					details.setPlatformId(account.getPlatformId());
					details.setPlatformName(account.getPlatformName());
					details.setTotalAmount(String.valueOf(totalAmount));
					details.setInsuranceAmount(String.valueOf(insAmount));
					details.setTotalCount(String.valueOf(totalCount));
					details.setRealAmount(String.valueOf(realAmount));
					details.setRegisterAmount(String.valueOf(regAmount));
					details.setRegisterRealAmount(String.valueOf(regRealAmount));
					details.setRegisterInsuranceAmount(String.valueOf(regInsAmount));
					details.setRegisterCount(String.valueOf(regCount));
					details.setMzFeeAmount(String.valueOf(mzAmount));
					details.setMzFeeInsuranceAmount(String.valueOf(mzInsAmount));
					details.setMzFeeRealAmount(String.valueOf(mzRealAmount));
					details.setMzFeeCount(String.valueOf(mzCount));
					details.setZyAmount(String.valueOf(zyAmount));
					details.setZyInsuranceAmount(String.valueOf(zyInsAmount));
					details.setZyRealAmount(String.valueOf(zyRealAmount));
					details.setZyCount(String.valueOf(zyCount));
					bills.add(details);
				}
				pat.setBillDetails(bills);
				pasts.add(pat);
			}
			response.setResultObject(pasts);
			response.setResultCodeAndMessage(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE);

		} catch (ParseException e) {
			logger.error("[FinanceServiceImpl.queryFinanceDetailsPatstatistics] -- ", e);
		}

		return response;
	}
	
	
	/**
	 * 流水明细及统计-收单机构订单流水明细 <br>
	 * yyt.pay.finance.details.thirdpayment.query
	 * 
	 * @param strJson
	 *            
	 * @return 
	 */
	public Map<String, Object> queryFinanceDetailsThirdpayment(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);
		
		if (StringUtils.isNotBlank(param.getString("yyt_order_no"))) {
			param.put("order_no", param.getString("yyt_order_no"));
		}
		if (StringUtils.isNotBlank(param.getString("pay_type"))) {
			param.put("pay_mode", param.getString("pay_type"));
		}
		if (StringUtils.isNotBlank(param.getString("payment_deal_id"))) {
			param.put("payment_deal_id", param.getString("payment_deal_id"));
		}
		validParam(param, "org_id,begin_pay_date,end_pay_date");

		Map<String, Object> mapReturn = new HashMap<String, Object>();
		mapReturn.put("records", ListUtils.EMPTY_LIST);

		mapReturn.put("platform_total_receive_amount", "0");

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return mapReturn;
		}

		try {
			PaymentCheckSourceFile paymentCheckSourceFile = JsonUtils.parseObject(strJson, PaymentCheckSourceFile.class);
			paymentCheckSourceFile.setOrgId(param.getString("org_id"));
			paymentCheckSourceFile.setBeginPayTime(beginPayDate + " 00:00:00");
			paymentCheckSourceFile.setEndPayTime(endPayDate + " 23:59:59");
			if(StringUtils.isNotBlank(param.getString("yyt_order_no"))){
				paymentCheckSourceFile.setOrderNo(param.getString("yyt_order_no"));
			}
			if(StringUtils.isNotBlank(param.getString("payment_deal_id"))){
				paymentCheckSourceFile.setPaymentDealId(param.getString("payment_deal_id"));
			}

			param.putAll(JsonUtils.parseObject(paymentCheckSourceFile));
			Long totalCount = 0L;
			Map<String,Object> mapCount =  paymentSourceFileDao.selectStat(paymentCheckSourceFile);
			if (mapCount != null) {
				if (mapCount.get("cnt") != null) {
					totalCount = Long.parseLong(mapCount.get("cnt").toString());
				}

				String pageNum = param.getString("page_num");

				if (totalCount > 0  && StringUtils.isNotBlank(pageNum)) {
					PageInfo pageInfo = initPageInfo(param);
					doPageInfo(pageInfo, totalCount);
					mapReturn.put("page_info", pageInfo);

				}
				List<PaymentCheckSourceFile> listSourceFile = this.listEntity(JsonUtils.toJsonString(param),
						PaymentCheckSourceFile.class, paymentSourceFileDao);
				mapReturn.put("records", listSourceFile);
				mapReturn.putAll(mapCount);
			}

		}
		catch (Exception e) {
			logger.error("流水明细及统计-平台订单流水明细:" + strJson, e);
			mapReturn = new HashMap<String, Object>();
			// throw new CallException("-1", "统计异常");
		}

		return mapReturn;
	}
	
	/**
	 * 
	 * 设置-对账生成-重置
	 * yyt.pay.finance.setting.bill.reset
	 * @param strJson org_id,begin_pay_date,end_pay_date
	 * @return 成功返回true，否则返回false
	 */
	public Boolean resetFinanceSettingBill(String strJson) {
		logger.info(strJson);
		boolean bFlag = false;
		try {
			JSONObject param = JsonUtils.parseObject(strJson);

			validParam(param, "org_id,begin_pay_date,end_pay_date");

			String beginTime = param.getString("begin_pay_date")+" 00:00:00";
			String endTime = param.getString("end_pay_date")+" 23:59:59";

			Response response = BaseService.getBaseClient().findOrgById(param.getString("org_id"));
			if (StringUtils.isNotBlank(response.getResult())) {
				Org org = JsonUtils.parseObject(response.getResult(),Org.class);
				List<Org> listOrg = new ArrayList<>();
				listOrg.add(org);
				JSONObject paramCheck = new JSONObject();
				paramCheck.put("org_id",org.getId());
				paramCheck.put("begin_pay_time", beginTime);
				paramCheck.put("end_pay_time", endTime);
				paramCheck.put("clear_flag", 1);
				if (param.containsKey("clear_flag")) {
					paramCheck.put("clear_flag", param.getInteger("clear_flag"));
				}
				
				
				response = checkPaymentService.clearCheckPaymentForDatas(JsonUtils.toJsonString(paramCheck));
				logger.info(JsonUtils.toJsonString(response));
				if ("0".equals(response.getResultCode())) {
					paramCheck = new JSONObject();
					paramCheck.put("org_id",org.getId());
					paramCheck.put("begin_pay_time",beginTime);
					paramCheck.put("end_pay_time",endTime);
					paramCheck.put("isClearHis",1);
					
					
					response = hisPayfinanceService.resetHisPayfinanceInfo(JsonUtils.toJsonString(paramCheck));
					logger.info(JsonUtils.toJsonString(response));
					if ("0".equals(response.getResultCode())) {
						bFlag = true;
					}
					else {
						logger.error("清除HIS数据异常" + strJson);
						throw new CallException("-1", "清除HIS数据异常");
					}

					
				}
				else {
					logger.error("清除平台数据异常" + strJson);
					throw new CallException("-1", "清除平台数据异常");
				}
				
			}
			else {
				logger.error("无法获得机构信息"+strJson);
				throw new CallException("-1", "无法获得机构信息");
			}
		} 
		 
		catch (CallException ce) {
			logger.error("重置数据发生异常" + strJson, ce);
			throw ce;
		}
		catch (Exception e) {
			logger.error("重置数据发生异常" + strJson, e);
			throw new CallException("-1", "重置数据发生异常");
		}
		return bFlag;

	}
	
	public final static ThreadLocal<JSONObject> thLogInfo = new ThreadLocal<JSONObject>();
	
	/**
	 * 生成对账数据(平台后台按钮入口)
	 * yyt.pay.finance.setting.bill.created
	 * 
	 * @param strJson org_id,begin_pay_date:YYYY-MM-DD,end_pay_date:YYYY-MM-DD
	 *            
	 * @return
	 *  full_success 是否完全成功<br>
	 *  has_exception 是否发生异常
	 */
	public Response createdFinanceSettingBill(String strJson) throws Exception {
		new Thread(new CreateBillRunnable(strJson)).start();
		logger.info("启动对账线程完毕");
		return new Response();
	}
;	
	/**
	 * 生成对账数据 <br>
	 * 
	 * @param strJson org_id,begin_pay_date:YYYY-MM-DD,end_pay_date:YYYY-MM-DD
	 *            
	 * @return
	 *  full_success 是否完全成功<br>
	 *  has_exception 是否发生异常
	 */
	public List<Map<String,Object>> createBill(String strJson) throws Exception {
		
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);

		validParam(param, "begin_pay_date,end_pay_date");
		
		param.put("batch_no", YYYYMMDDHHMISS14.format(new Date()));
		thLogInfo.set(param);
		
		List<Map<String,Object>> listReturn = new ArrayList<>();
		List<Org> orgs = new ArrayList<>();

		String orgId = param.getString("org_id");

		if ("ALL".equals(orgId)) {
        	logger.info("读取所有系统配置的机构进行对账");
        	Response orgResponse = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_ORG_USABLE, null);
        	orgs = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        	logger.info("需要对账的机构列表："+JsonUtils.toJsonString(orgs));
        }
		else {
			Response response = BaseService.getBaseClient().findOrgById(orgId);
			Org org = JsonUtils.parseObject(response.getResult(),Org.class);
			if (org == null) {
				throw new CallException("-1", "无法获取指定医院：org_id="+ orgId);
			}
			orgs.add(org);
		}
		
		for (Org org : orgs) {
			param.put("org_id", org.getId());
			boolean bFlag = resetFinanceSettingBill(JsonUtils.toJsonString(param));
			if (bFlag) {
				List<Org> listOrg = new ArrayList<>();
				listOrg.add(org);
				List<Map<String,Object>> listReturnOne = createBill(listOrg, param.getString("begin_pay_date"), param.getString("end_pay_date"));
				listReturn.addAll(listReturnOne);
			}
			else {
				
				logger.error("重置数据异常，无法重新生成数据");
				throw new CallException("-1", "重置数据异常，无法重新生成数据");
			}
		}
		thLogInfo.remove();
		return listReturn;
		
	}
	/**
	 * 
	 * @param beginDate YYYY-MM-DD
	 * @param endDate YYYY-MM-DD
	 * @return 
	 *  full_success 是否完全成功<br>
	 *  has_exception 是否发生异常
	 */
	public List<Map<String,Object>>  createBill(List<Org> orgs,String beginDate,String endDate) {
		List<Map<String,Object>> listReturn = new ArrayList<>();
		Calendar cStart = Calendar.getInstance();
		cStart.setTime(DateUtils.StringToDate(beginDate));

		Calendar cEnd = Calendar.getInstance();
		cEnd.setTime(DateUtils.StringToDate(endDate));

		// 间隔天数
		int days = Math.abs(DateUtils.getDaysBetween(cEnd, cStart)) + 1;

		logger.info("days=" + days);

		//0b0ed0499a8911e6951000163e00175d
		for (int i = 0; i < days; i++) {
			for (Org org : orgs) {
				String date = YYYYMMDD.format(cStart.getTime());
				List<Org> listTmp = new ArrayList<>();
				listTmp.add(org);
				Map<String,Object> mapResult = createBill(listTmp, date);
				listReturn.add(mapResult);
			}
//			String date = YYYYMMDD.format(cStart.getTime());
//			Map<String,Object> mapResult = createBill(orgs, date);
//			listReturn.add(mapResult);
			cStart.add(Calendar.DATE, 1);
		}
		
		return listReturn;
	}

	/**
	 * 生成对账主程序
	 * @param orgs 要对账的机构，如果为空或null，则对账所有有效配置的机构
	 * @param date YYYY-MM-DD
	 * @return 
	 *  full_success 是否完全成功<br>
	 *  has_exception 是否发生异常
	 */
	public Map<String,Object> createBill(List<Org> orgs,String date) {
		
		Map<String,Object> mapReturn = new HashMap<>();
		mapReturn.put("date",date);
		boolean fullSuccess = false;
		
		//存放调用获取第三方数据过程的返回信息,key=orgId,value=返回值Map对象
        Map<String,JSONObject> mapGetDataReturnInfo = new LinkedHashMap<>();
        mapReturn.put("mapGetDataReturnInfo", mapGetDataReturnInfo);
        
        //存放调用第三方对账过程的返回信息,key=orgId,value=返回值Map对象
        Map<String,JSONObject> mapThirdCheckAccountReturnInfo = new LinkedHashMap<>();
        mapReturn.put("mapThirdCheckAccountReturnInfo", mapThirdCheckAccountReturnInfo);
        
        //存放执行获取第三方数据过程是否成功,key=orgId
        Map<String,Boolean> mapGetDataSuccess = new LinkedHashMap<>();
        mapReturn.put("mapGetDataSuccess", mapGetDataSuccess);
        
        //存放执行第三方对账成功的,key=orgId
        Map<String,Boolean> mapThirdCheckAccountSuccess = new LinkedHashMap<>();
        
        //第三方对账是否发生异常
        boolean checkThirdAccountExceptionFlag = false;
        
        //已经存在的，需要对账的账户支付设置
        Map<String,Object> mapPaymentSettingExist = new LinkedHashMap<>();
		try {

	        Map<String, Object> map = null;
	        String yesDate = null;
	        
	        if (StringUtils.isBlank(date)) {
	        	date = YYYYMMDD.format(new Date());
	            logger.info("[platformCheckPayment]传入日期：" + date);
	            yesDate = DateUtils.getDateForType(date , 2);
	            logger.info("[platformCheckPayment]获取昨天日期：" + yesDate);
	        }
	        else {
//	            yesDate = DateUtils.getDateForType(date , 2);
	            yesDate = date;
	            date =  DateUtils.getDateForType(yesDate , 1);
	            logger.info("[platformCheckPayment]获取昨天日期：" + yesDate);
	        }
	        
	        //获取医院所关联应用 sys_org_app
	        
	        if (CollectionUtils.isEmpty(orgs)) {
	        	logger.info("读取所有系统配置的机构进行对账");
	        	Response orgResponse = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_ORG_USABLE, null);
	        	orgs = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
	        	logger.info("需要对账的机构列表："+JsonUtils.toJsonString(orgs));
	        }
	        

	        List<String> orgOks = new ArrayList<String>();
	        List<String> orgOksFirst = new ArrayList<String>();
	        List<String> orgErrors = new ArrayList<String>();
			List<String> orgList = new ArrayList<String>();
	        List<FutureTask<Object>> futureList = new ArrayList<FutureTask<Object>>();
	        FutureTask future = null;
	        FutureTask hisFuture = null;

			logger.info("<<< 1.获取可用组织 --- orgs：" + JsonUtils.toJsonString(orgs));
	        //<<<< 1.根据组织配置获取第三方账单入库及his账单拉取入库
	        if (orgs.size() > 0) {
	            for (Org org : orgs) {
	                String branchCode = "";
	                if (org.getOrgType() == 2) {
	                    branchCode = org.getOrgCode();
	                }

					//检查规则配置表，该组织是否参与对账
					map = new HashMap<String, Object>();
					map.put("attribute_name" , Config.RULE_ATTRIBUTE_NAME);
					map.put("org_code" , org.getOrgCode());
					Response response = BaseService.callHumpFromInternal(MethodRouter.FIND_SYS_RULE_ATTRIBUTE, JSON.toJSONString(map));
					if(StringUtils.isNotBlank(response.getResult())){
						Rule rule = JsonUtils.parseObject(response.getResult(), Rule.class);
						if(rule != null){
							if("1".equals(rule.getAttributeProperties())){
								logger.info("<<< 2.获取开通对账属性配置 --- 根据orgCode：" + org.getOrgCode() + "成功获取该医院："+ org.getOrgName() +" 属性配置.");

								//根据orgId获取setting配置
								PlatformAccount account = new PlatformAccount();
								account.setOrgId(org.getId());
								List<PlatformAccount> platformAccounts = platformAccountDao.select(account);

								logger.info("<<< 3.获取该医院账户配置 --- 对账医院：" + org.getOrgName() + "，成功获取账户PlatformAccounts：" +  JsonUtils.toJsonString(platformAccounts));

								List<String> payAppIds = new ArrayList<String>();
								for (PlatformAccount platformAccount : platformAccounts) {
									if(!payAppIds.contains(platformAccount.getPayAppId())){
										payAppIds.add(platformAccount.getPayAppId());
									}else{
										continue;
									}
									PaymentSetting paymentSetting = new PaymentSetting();
									paymentSetting.setPayAppId(platformAccount.getPayAppId());
									paymentSetting.setCheckFlag((short) 1);
									List<PaymentSetting> paymentSettings = paymentSettingDao.select(paymentSetting);

									logger.info("<<< 4.获取该支付配置 --- 对账医院：" + org.getOrgName() + "，根据PayAppId：" +  platformAccount.getPayAppId() +" ,成功获取支付配置：" + JsonUtils.toJsonString(paymentSettings));

									if(paymentSettings.size() > 0){
										if (!orgOks.contains(org.getId())) {
											orgOks.add(org.getId());
										}
										for (PaymentSetting paySetting : paymentSettings) {

											if (mapPaymentSettingExist.containsKey(paySetting.getId())) {
												continue;
											}
											mapPaymentSettingExist.put(paySetting.getId(), paySetting);

											logger.info(">>>>执行开始：" + org.getOrgName() + ",appId:" + paySetting.getPayAppId() + ",payMode:" + paySetting.getPayMode());
											future = new FutureTask(new PaymentCheckRunnable(paySetting, yesDate, org.getId(), org.getOrgName(),thLogInfo.get()));
											futureList.add(future);

											logger.info(">>> paymentSetting.getOrgId():" + paymentSetting.getOrgId());
											if(!orgList.contains(paymentSetting.getOrgId())){
												//获取his账单
												hisFuture = new FutureTask(new HisPayfinanceRunnable(org.getId(), org.getOrgName(), branchCode, org.getOrgCode(), yesDate, date, "0",thLogInfo.get()));
												futureList.add(hisFuture);
												orgList.add(paymentSetting.getOrgId());
												logger.info(">>> orgList.json:" + JSON.toJSONString(orgList));
											}
										}

										logger.info("appId:"+ platformAccount.getPayAppId() +",打印mapPaymentSettingExist内容：" + JSON.toJSONString(mapPaymentSettingExist));
									}
									else {
										mapReturn.put("createBillGetDataMessage", "check:没有设置对账:"+platformAccount.getAccountName()+" payAppId="+ platformAccount.getPayAppId());
										logger.info("check:没有设置对账:"+platformAccount.getAccountName()+" payAppId="+ platformAccount.getPayAppId());
									}
								}
							}
						}
	                }
	                else {
	                	mapReturn.put("createBillGetDataMessage", "check:没有规则:"+org.getOrgName()+ " orgCode="+org.getOrgCode());
	                	logger.warn("check:没有规则:"+org.getOrgName()+ " orgCode="+org.getOrgCode());
	                }
	            }
	        }
	        else {
	        	mapReturn.put("createBillGetDataMessage", "check:没有需要对账的机构");
	        	logger.warn("check:没有需要对账的机构");
	        }
	        
	        
	        for (String orgId : orgOks) {
	        	orgOksFirst.add(orgId);
	        }
	        int sizeOrgOks = orgOks.size();
	        ExecutorService threadPool = Executors.newFixedThreadPool(10);
	        List<String> removeList = new ArrayList<>();
	        if(futureList.size() > 0){
	        	
	            //线程执行
	            for (FutureTask<Object> task : futureList) {
	                threadPool.submit(task);
	            }

	            for (FutureTask<Object> task : futureList) {
	                try {
	                    Response futureRes = (Response) task.get();
	                    logger.info("futureRes:"+JsonUtils.toJsonString(futureRes));
	                    if (!"0".equals(futureRes.getResultCode())) {	//线程执行失败
	                        String orgId = futureRes.getResult();
	                        if (orgId.startsWith("{")) {
	                        	JSONObject mapInfo = JsonUtils.parseObject(orgId);
	                        	orgId = mapInfo.getString("org_id");
	                        }
	                        logger.error("Future error message: 组织id——" + orgId +"——"+ futureRes.getResultMessage());
	                        if (orgOks.contains(orgId)) {
	                            orgOks.remove(orgId);
	                        }

	                        if(!orgErrors.contains(orgId)){
	                            orgErrors.add(orgId);
	                        }
	                        mapGetDataSuccess.put(orgId, false);
	                        
	                    }
	                    else {	//线程执行成功
	                    	String orgId = futureRes.getResult();
	                        if (orgId.startsWith("{")) {
	                        	JSONObject mapInfo = JsonUtils.parseObject(orgId);
	                        	orgId = mapInfo.getString("org_id");
	                        }
	                    	mapGetDataSuccess.put(orgId, true);
	                    	
	                    }

	                    if (StringUtils.isNotBlank(futureRes.getResult()) && futureRes.getResult().startsWith("{")) {
							JSONObject mapInfo = JsonUtils.parseObject(futureRes.getResult());

							mapGetDataReturnInfo.put(mapInfo.getString("org_id")+"_"+mapInfo.getString("check_data_type"), mapInfo);

							// 检查是否需要退出对账
//							if (mapInfo.containsKey("stop_finance_flag")
//									&& mapInfo.getBooleanValue("stop_finance_flag")) {
//								mapStopCheckAccount.put(mapInfo.getString("org_id"), mapInfo);
//							}
	                    }
	                } catch (Exception e) {
	                	logger.error("futureList数据获取线程执行异常",e);
	                    logger.error("[CheckPaymentServiceImpl.doExecute.jobs.futureTaskList]", e);
	                
	                }
	            }

	            logger.info(">>>线程执行完毕！总线程数：" + futureList.size());
	            logger.info(">>>线程执行成功ok数：" + orgOks.size() +",info:" + orgOks.toString());
	            threadPool.shutdown();
	            
	            
	            //失败数据回滚（数据清除）
	            if(orgErrors.size() > 0){
	                for (String errorOrgId : orgErrors) {
	                    map = new HashMap<String, Object>();
	                    map.put("payTime", yesDate);
	                    map.put("orgId", errorOrgId);
	                    map.put("clearFlag", 1);
	                    Response response = checkPaymentService.clearCheckPaymentForDatas(JSON.toJSONString(map));
	                    logger.info("回滚数据 clearCheckPaymentForDatas返回值："+JsonUtils.toJsonString(response));
	                    logger.info(errorOrgId + " 回滚（数据清除）" + response.getResultCode() + "-" +response.getResultMessage());
	                    
	                    //清除HIS数据
	                    JSONObject paramCheck = new JSONObject();
						paramCheck.put("org_id",errorOrgId);
						paramCheck.put("pay_time",yesDate);
						paramCheck.put("isClearHis",1);
						
						response = hisPayfinanceService.resetHisPayfinanceInfo(JsonUtils.toJsonString(paramCheck));
						if ( ! "0".equals(response.getResultCode())) {
							logger.error("清除HIS数据异常" + JsonUtils.toJsonString(paramCheck));
						}
	                }
	            }



				//<<<< 2.执行第三方与平台对账
	            try {
	                if (orgOks.size() > 0) {
	                    for (String orgId : orgOks) {
	                        logger.info(">>>[第三方与平台对账]ORG_ID：" + orgId);
	                        map = new HashMap<String, Object>();
	                        map.put("date", yesDate);
	                        map.put("orgId", orgId);
	                        JSONObject jsonThird  = thirdFinanceService.checkingThirdfinance(JsonUtils.toJsonString(map));
	                        mapThirdCheckAccountReturnInfo.put(jsonThird.getString("org_id"),jsonThird);
				            logger.info("checkingThirdfinance返回值："+JsonUtils.toJsonString(jsonThird));
				            int sourceCount = jsonThird.getIntValue("count");
				            if (jsonThird.getBooleanValue("is_success")) {
				            	logger.info("对账成功!---执行对账成功录入条目：" + sourceCount);
				            	mapReturn.put("createBillCheckingThirdfinanceMessage", "对账成功!---执行对账成功录入条目：" + sourceCount);
				            	mapThirdCheckAccountSuccess.put(jsonThird.getString("org_id"),true);
				            }
				            else {
				            	logger.error("对账过程中发生过异常");
				            	logger.error("执行对账成功录入条目：" + sourceCount);
				            	mapReturn.put("createBillCheckingThirdfinanceMessage", "对账过程中发生过异常---执行对账成功录入条目：" + sourceCount);
				            	mapThirdCheckAccountSuccess.put(jsonThird.getString("org_id"),false);
				            }

//				            
//	                        int sourceCount = thirdFinanceService.checkingThirdfinance(JSON.toJSONString(map));
//	                        logger.info("<<<<<--组织：" + orgId + ",第三方与平台对账：对账完毕，对账笔数：" + sourceCount);
//
//	                        if (sourceCount == 0) {
//	                            logger.info(orgId+"第三方与平台对账失败，对账数为0");
//	                            removeList.add(orgId);
//	                        }
	                    }
	                }

	                if(removeList.size() > 0){
	                    orgOks.removeAll(removeList);
	                }
	                
	                checkThirdAccountExceptionFlag = false;
	            } 
	            catch (CallException ce) {
	            	checkThirdAccountExceptionFlag = true;
	            	mapReturn.put("createBillThridCheckAccountMessage", "执行第三方与平台对账异常:"+ce.getMessage());
	            	logger.error("执行第三方与平台对账异常",ce);
	            }
	            catch (Exception e) {
	            	checkThirdAccountExceptionFlag = true;
	            	mapReturn.put("createBillThridCheckAccountMessage", "执行第三方与平台对账异:"+e.getMessage());
	            	logger.error("执行第三方与平台对账异常",e);
	            }
	            
	            mapReturn.put("checkThirdAccountExceptionFlag", checkThirdAccountExceptionFlag);

				//<<<< 3.执行his与平台对账
	            try {
	                if (orgOks.size() > 0) {
	                	List<String> hisCheckAccountErrorList = new ArrayList<>();
	                    for (String orgId : orgOks) {
	                        logger.info(">>>[HIS与平台对账]ORG_ID：" + orgId);
	                        map = new HashMap<String, Object>();
	                        map.put("orgId", orgId);
	                        map.put("payTime", yesDate);
	                        try {
								hisPayfinanceService.checkHisPayFinancePlat(JSON.toJSONString(map));
							} catch (Exception e) {
								logger.error("HIS对账错误：orgId="+orgId,e);
								hisCheckAccountErrorList.add(orgId);
								
								//事件信息
					            Map<String,Object> paramEvent = new HashMap<>();
					        	paramEvent.put("event_code", "CK_PLATFORM_CHECK_HIS");
					        	paramEvent.put("module_code", "CHECK_ACCOUNT");
					        	Response responseEvent = BaseService.callHumpFromInternal("yyt.base.event.get", JsonUtils.toJsonString(paramEvent));
					        	if (StringUtils.isNotBlank(responseEvent.getResult())) {
					        		EventVo event = JsonUtils.parseObject(responseEvent.getResult(), EventVo.class);
					        		FinanceServiceImpl.sendSmsForFail(orgId,"CK_PLATFORM_CHECK_PAY", null, yesDate, YYYYMMDDHHMISS14.format(new Date()),event.getEventLevel()+"","HIS对账失败"+e.getMessage());
					        	}
					        	else {
					        		logger.error("获取系统事件定义事事件，无法获取事件级别：CK_PLATFORM_CHECK_PAY");
					        		FinanceServiceImpl.sendSmsForFail(orgId,"CK_PLATFORM_CHECK_PAY",null, yesDate, YYYYMMDDHHMISS14.format(new Date()),"-1","HIS对账失败"+e.getMessage());
					        	}
							}
	                        
	                    }
	                    mapReturn.put("hisCheckAccountErrorList", hisCheckAccountErrorList);
	                    orgOks.removeAll(hisCheckAccountErrorList);
	                    
	                } else {
	                	
	                    logger.info("对账失败！All组织对账异常..orgOks.size < 0");
	                    mapReturn.put("his_check_account", "没有需要进行HIS对账的机构");
	                }
	                
	                if (orgOks.size() == sizeOrgOks) {
	                	fullSuccess = true;
	                }
	            } 
	            catch (CallException ce) {
	            	mapReturn.put("createBillHisCheckAccountMessages", "HIS与平台对账异常："+ce.getMessage());
	            	logger.error("HIS与平台对账",ce);
	            	throw ce;
	            }
	            catch (Exception e) {
	            	mapReturn.put("createBillHisCheckAccountMessages", "HIS与平台对账异常"+e.getMessage());
	            	logger.error("HIS与平台对账",e);
	            }
	        }
	        else {
	        	mapReturn.put("createBillFutureList","futureList为空,没有符合条件，需要对账的数据");
	        	logger.warn("futureList为空");
	        }



			//<<<< 4.发送执行结果短信并日志入库
			for (String orgId : orgOksFirst) {
				if (orgOks.contains(orgId)) {
					//查询差错金额和差错笔数
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("begin_pay_date" , yesDate);
					jsonObject.put("end_pay_date" , yesDate);
					jsonObject.put("org_id" , orgId);
					Map<String, Object> mapParam = null;
					List<Map<String, Object>> mapLists = queryFinanceSummaryTimeperiod(jsonObject.toJSONString());
					for (Map<String, Object> maps : mapLists) {
						if(maps.containsKey("record_sum")){
							mapParam = maps;
							break;
						}
					}

					logger.info("发送成功短信前，最后总览数据Json：" + JsonUtils.toJsonString(mapLists));

					Map<String, Object> recordSum = (Map<String, Object>) mapParam.get("record_sum");

					logger.info("发送成功短信前，最后recordSum数据Json：" + JsonUtils.toJsonString(recordSum));

					String diffAmount = "0";
					String diffCount = "0";

					if(mapParam != null && recordSum != null){
						String amount = String.valueOf(recordSum.get("difference_amount"));
						diffAmount = BigDecimalUtil.changeF2Y(amount);
						diffCount =String.valueOf(recordSum.get("difference_number"));
					}

					//成功
					Map<String,Object> paramOrg = new HashMap<>();
					paramOrg.put("id", orgId);
					JSONObject jsonOrg = JsonUtils.parseObject(BaseService.callHumpFromInternal("yyt.base.org.by.id.find", JsonUtils.toJsonString(paramOrg)).getResult());
					FinanceServiceImpl.sendSmsForSuccess(orgId,"CK_CHECK_SUCESSFUL",jsonOrg.getString("org_name"), yesDate, YYYYMMDDHHMISS14.format(new Date()) , diffCount , diffAmount);


					FinanceServiceImpl.insertLog(orgId, "CK_CHECK_SUCESSFUL", "对账成功");

				}
				else {
					//失败
					//拉取第三方数据和平台对账的短消息已经发送
				}
			}
		}
		catch (Exception ex) {
			mapReturn.put("createBillException","生成对账异常：org="+JsonUtils.toJsonString(orgs)+",date="+date);
			logger.error("生成对账异常：org="+JsonUtils.toJsonString(orgs)+",date="+date,ex);
			mapReturn.put("has_exception", true);
		}
		
		mapReturn.put("full_success", fullSuccess);
		if ( ! mapReturn.containsKey("has_exception")) {
			mapReturn.put("has_exception", false);
		}
		logger.info(JsonUtils.toJsonString(mapReturn));
		return mapReturn;
    }
	
	/**
	 * 设置-运行日志
	 * yyt.pay.finance.setting.log
	 * @param strJson
	 * @return
	 */
	public Map<String,Object> logFinanceSetting(String strJson) {
		return BaseService.getBaseClient().listLog(strJson);
	}

	
	/**
	 * 
	 * 设置-医院列表
	 * yyt.pay.finance.setting.hospital.query
	 * @param strJson
	 * @return
	 */
	public Map<String,Object> queryFinanceSettingHospital(String strJson) {
		Map<String,Object> param = JsonUtils.parseObject(strJson);
		param.put("attribute_name", "CheckAccountFlag");
		Map<String,Object> mapReturn = new HashMap<>();
		Response response = BaseService.callHumpFromInternal("yyt.base.rule.query", JsonUtils.toJsonString(param));
		logger.info(JsonUtils.toJsonString(response));
		if ("0".equals(response.getResultCode())) {
			List<Rule> rules = JsonUtils.parseArray(response.getResult(), Rule.class);
			List<Rule> arrayList = new ArrayList<Rule>();
			for (Rule rule : rules) {
				if("1".equals(rule.getAttributeProperties())){
					arrayList.add(rule);
				}
			}
			if (response.getResult() != null) {
				mapReturn.put("records", JsonUtils.parseArray(JsonUtils.toJsonString(arrayList)));
			}
			else {
				mapReturn.put("records",Collections.EMPTY_LIST);
			}
		}
		else {
			mapReturn.put("records", Collections.EMPTY_LIST);
		}
		return mapReturn;
	}
	
	/**
	 * 对账总览
	 *
	 * @param strJson
	 * @return org_id,begin_pay_date,end_pay_date
	 * @interfacename yyt.pay.finance.details.patstatistics.query
	 */
	public List<Map<String, Object>> queryFinanceDetailsPatstatisticsNew(String strJson) {
		logger.info(strJson);
		JSONObject param = JsonUtils.parseObject(strJson);
		String orgId = param.getString("org_id");

		validParam(param, "org_id,begin_pay_date,end_pay_date");

		List<Map<String, Object>> listReturn = new ArrayList<>();

		String beginPayDate = param.getString("begin_pay_date");
		String endPayDate = param.getString("end_pay_date");

		if (endPayDate.compareTo(beginPayDate) < 0) {
			logger.error("统计开始日期必须小于结束日期：" + strJson);
			return listReturn;
		}

		Calendar cStart = Calendar.getInstance();
		cStart.setTime(DateUtils.StringToDate(beginPayDate));

		Calendar cEnd = Calendar.getInstance();
		cEnd.setTime(DateUtils.StringToDate(endPayDate));

		// 间隔天数
		int days = Math.abs(DateUtils.getDaysBetween(cEnd, cStart)) + 1;

		logger.info("days=" + days);

		// 查询org下平台信息
		try {
			int hisReceiveAmountAll = 0;
			int platformReceiveAmountAll = 0;
			int differenceAmountAll = 0;
			int differenceNumberAll = 0;
			for (int i = 0; i < days; i++) {

				int hisReceiveAmountOneDay = 0;
				int platformReceiveAmountOneDay = 0;
				int differenceAmountOneDay = 0;
				int differenceNumberOneDay = 0;

				beginPayDate = YYYYMMDD.format(cEnd.getTime()) + " 00:00:00";
				endPayDate = YYYYMMDD.format(cEnd.getTime()) + " 23:59:59";

				Map<String, Object> mapOneDay = new LinkedHashMap();
				mapOneDay.put("pay_date", YYYYMMDD.format(cEnd.getTime()));

				ArrayList<String> platformIds = new ArrayList<String>();
				PlatformAccount platformAccount = new PlatformAccount();
				platformAccount.setOrgId(orgId);
				if (StringUtils.isNotBlank(param.getString("platform_id"))) {
					platformAccount.setPlatformId(param.getString("platform_id"));
				}
				List<PlatformAccount> platformAccounts = platformAccountDao.select(platformAccount);
				logger.info("platformAccounts-size=" + platformAccounts.size());

				List<Map> listPlatform = new ArrayList<>();
				mapOneDay.put("records", listPlatform);

				Map<String, List<Map>> existCheckMap = new HashMap<>();

				for (PlatformAccount account : platformAccounts) {
					JSONObject record = JsonUtils.parseObject(account);
					platformIds.add(account.getPlatformId());
					if (!existCheckMap.containsKey(account.getPlatformId())) {

						Map<String, Object> mapPlatform = new HashMap<>();
						mapPlatform.put("platform_id", account.getPlatformId());
						mapPlatform.put("platform_name", account.getPlatformName());
						List<Map> listAccount = new ArrayList<>();
						listAccount.add(record);
						mapPlatform.put("accounts", listAccount);
						listPlatform.add(mapPlatform);

						existCheckMap.put(account.getPlatformId(), listAccount);
					} else {
						List<Map> listAccount = existCheckMap.get(account.getPlatformId());
						listAccount.add(record);
					}
					HisOrder sumHisOrder = hisOrderDao.queryFinanceSummaryOneday(beginPayDate, endPayDate,
							account.getPayAppId(), account.getPlatformId(), orgId);

					record.put("pay_app_name", account.getPlatformName());
					record.put("his_receive_amount", "0");
					record.put("platform_receive_amount", "0");
					record.put("difference_amount", "0");
					record.put("difference_number", "0");
					if (sumHisOrder != null) {
						// 医院应收金额
						record.put("his_receive_amount", sumHisOrder.getPayAmount());
						hisReceiveAmountAll += getNotZeroInteger(sumHisOrder.getPayAmount());
						hisReceiveAmountOneDay += getNotZeroInteger(sumHisOrder.getPayAmount());
					}

					PaymentJournal sumPaymentJournal = paymentJournalDao.queryFinanceSummaryOneday(beginPayDate,
							endPayDate, account.getPayAppId(), account.getPlatformId(), orgId);
					if (sumPaymentJournal != null) {
						// 平台实收金额
						record.put("platform_receive_amount", sumPaymentJournal.getPayAmount());
						platformReceiveAmountAll += getNotZeroInteger(sumPaymentJournal.getPayAmount());
						platformReceiveAmountOneDay += getNotZeroInteger(sumPaymentJournal.getPayAmount());
					}

					HisOrderCheckedError sumHisOrderCheckedError = hisOrderCheckedErrorDao.queryFinanceSummaryOneday(
							beginPayDate, endPayDate, account.getPayAppId(), account.getPlatformId(), orgId);
					if (sumHisOrderCheckedError != null) {

						// 差错金额
						record.put("difference_amount", sumHisOrderCheckedError.getYytPayAmount());

						// 差错笔数
						record.put("difference_number", sumHisOrderCheckedError.getYytTotalAmount());

						differenceAmountAll += getNotZeroInteger(sumHisOrderCheckedError.getYytPayAmount());
						differenceNumberAll += getNotZeroInteger(sumHisOrderCheckedError.getYytTotalAmount());
						differenceAmountOneDay += getNotZeroInteger(sumHisOrderCheckedError.getYytPayAmount());
						differenceNumberOneDay += getNotZeroInteger(sumHisOrderCheckedError.getYytTotalAmount());
					}

				}

				Map<String, Object> recordSum = new LinkedHashMap<>();

				recordSum.put("his_receive_amount", hisReceiveAmountOneDay);
				recordSum.put("platform_receive_amount", platformReceiveAmountOneDay);
				recordSum.put("difference_amount", differenceAmountOneDay);
				recordSum.put("difference_number", differenceNumberOneDay);

				mapOneDay.put("record_sum", recordSum);

				listReturn.add(mapOneDay);

				cEnd.add(Calendar.DATE, -1);

			} // for

			// 单日统计不需要执行总体统计
			if (!param.containsKey("not_sum_all_flag")) {
				Map<String, Object> recordSumAll = new LinkedHashMap<>();
				recordSumAll.put("his_receive_amount", hisReceiveAmountAll);
				recordSumAll.put("platform_receive_amount", platformReceiveAmountAll);
				recordSumAll.put("difference_amount", differenceAmountAll);
				recordSumAll.put("difference_number", differenceNumberAll);
				listReturn.add(recordSumAll);
			}

			logger.debug(JsonUtils.toJsonString(listReturn));
			logger.info("queryFinanceSummaryTimeperiod end");

			return listReturn;

		} catch (Exception e) {
			logger.error("对账总览异常:" + strJson, e);
			listReturn = new ArrayList();
			// throw new CallException("-1", "统计异常");
		}

		return listReturn;
	}

	/**
	 * 查询对账汇总数据
	 *
	 * @param datas
	 * @return
	 * @interfaceName: yyt.pay.finance.summary.query
	 */
	@Override
	public ResponseObject queryFinanceSummary(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);

		if (StringUtils.isNotBlank(datas)) {

			String orgId = dataMap.get("org_id");
			String orgName = dataMap.get("org_name");
			String checkTime = dataMap.get("check_time");

			List<FinanceSummaryVo> fsList = new ArrayList<FinanceSummaryVo>();

			checkTime = DateUtils.getDateForType(checkTime, 1);// 日期加一天

			String beginCheckTime = checkTime + " 00:00:00";
			String endCheckTime = checkTime + " 23:59:59";

			// 查询组织下的所有机构
			Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_APP_DEVELOP_LIST,
					JsonUtils.toJsonString(orgId));
			if ("0".equals(baseResp.getResultCode())) {
				List<OrgAppDevelopVo> developVos = JsonUtils.parseArray(baseResp.getResult(), OrgAppDevelopVo.class);
				for (OrgAppDevelopVo developVo : developVos) {
					FinanceSummaryVo financeSummaryVo = new FinanceSummaryVo();
					FinanceSummaryVo hisVo = paymentSourceFileDao.selectHisReceiveAmount(beginCheckTime, endCheckTime,
							orgId, developVo.getPlatformId());
					financeSummaryVo.setHis_alipay_receive_amount(hisVo.getHis_alipay_receive_amount());
					financeSummaryVo.setHis_wechat_receive_amount(hisVo.getHis_wechat_receive_amount());
					financeSummaryVo.setHis_receive_amount(hisVo.getHis_receive_amount());

					FinanceSummaryVo realVo = paymentSourceFileDao.selectReceiveRealAmount(beginCheckTime, endCheckTime,
							orgId, developVo.getPlatformId());
					financeSummaryVo.setAlipay_receive_real_amount(realVo.getAlipay_receive_real_amount());
					financeSummaryVo.setWechat_receive_real_amount(realVo.getWechat_receive_real_amount());

					financeSummaryVo.setPlatform_id(developVo.getPlatformId());
					financeSummaryVo.setPlatform_name(developVo.getPlatformName());

					fsList.add(financeSummaryVo);
				}

				response.setResultObject(JsonUtils.toJsonString(fsList));
				response.setResultCodeAndMessage("0", "查询成功!-1");

			} else {
				FinanceSummaryVo financeSummaryVo = new FinanceSummaryVo();

				logger.info(orgId + "：该组织下不存在develop！");
				// 获取微信、支付宝实收金额;医院应收总金额
				FinanceSummaryVo hisVo = paymentSourceFileDao.selectHisReceiveAmount(beginCheckTime, endCheckTime,
						orgId, null);
				financeSummaryVo.setHis_alipay_receive_amount(hisVo.getHis_alipay_receive_amount());
				financeSummaryVo.setHis_wechat_receive_amount(hisVo.getHis_wechat_receive_amount());
				financeSummaryVo.setHis_receive_amount(hisVo.getHis_receive_amount());

				FinanceSummaryVo realVo = paymentSourceFileDao.selectReceiveRealAmount(beginCheckTime, endCheckTime,
						orgId, null);
				financeSummaryVo.setAlipay_receive_real_amount(realVo.getAlipay_receive_real_amount());
				financeSummaryVo.setWechat_receive_real_amount(realVo.getWechat_receive_real_amount());

				financeSummaryVo.setPlatform_id(orgId);
				financeSummaryVo.setPlatform_name(orgName);

				fsList.add(financeSummaryVo);
				response.setResultObject(JsonUtils.toJsonString(fsList));
				response.setResultCodeAndMessage("0", "查询成功!-2");
			}

		} else {
			response.setResultObject(null);
			response.setResultCodeAndMessage("5001", "查询失败!");
		}

		return response;
	}

	/**
	 * 按渠道查询对账汇总数据
	 *
	 * @param datas
	 * @return
	 * @interfaceName: yyt.pay.finance.summary.by.channel.query
	 */
	@Override
	public ResponseObject queryFinanceSummaryByChannel(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);

		String orgId = dataMap.get("org_id");
		String orgName = dataMap.get("org_name");
		String checkTime = dataMap.get("check_time");
		String payMode = dataMap.get("pay_mode");

		List<FinanceChannelVo> fcList = new ArrayList<FinanceChannelVo>();

		checkTime = DateUtils.getDateForType(checkTime, 1);// 日期加一天

		String beginCheckTime = checkTime + " 00:00:00";
		String endCheckTime = checkTime + " 23:59:59";

		// 查询组织下的所有机构
		Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_APP_DEVELOP_LIST,
				JsonUtils.toJsonString(orgId));
		if ("0".equals(baseResp.getResultCode())) {
			List<OrgAppDevelopVo> developVos = JsonUtils.parseArray(baseResp.getResult(), OrgAppDevelopVo.class);
			for (OrgAppDevelopVo developVo : developVos) {

				FinanceChannelVo channelVo = new FinanceChannelVo();

				// 获取his实收金额
				FinanceChannelVo realVo = paymentJournalDao.selectSummaryRealHis(orgId, beginCheckTime, endCheckTime,
						payMode, developVo.getPlatformId());
				channelVo.setHis_receive_real_amount(realVo.getHis_receive_real_amount());
				channelVo.setHis_receive_real_pay_count(realVo.getHis_receive_real_pay_count());
				channelVo.setHis_receive_real_pay_amount(realVo.getHis_receive_real_pay_amount());
				channelVo.setHis_receive_real_refund_count(realVo.getHis_receive_real_refund_count());
				channelVo.setHis_receive_real_refund_amount(realVo.getHis_receive_real_refund_amount());

				// 统计：核实金额计算 ~ 支付：核算实收数据 =
				// 应收数据+【上日存疑（院方多）-上日存疑院方多转差错】-【上日存疑（院方少）-上日存疑院方少转差错】-当日存疑（院方多）+当日存疑（院方少）
				FinanceChannelVo costVo = hisOrderDao.selectCosting(orgId, payMode, beginCheckTime, endCheckTime,
						developVo.getPlatformId());
				channelVo.setHis_receive_pay_count(costVo.getHis_receive_pay_count());
				channelVo.setHis_receive_pay_amount(costVo.getHis_receive_pay_amount());
				channelVo.setHis_pay_refund_count(costVo.getHis_pay_refund_count());
				channelVo.setHis_pay_refund_amount(costVo.getHis_pay_refund_amount());

				channelVo.setPlatform_id(developVo.getPlatformId());
				channelVo.setPlatform_name(developVo.getPlatformName());

				fcList.add(channelVo);
			}

			response.setResultObject(JsonUtils.toJsonString(fcList));
			response.setResultCodeAndMessage("0", "查询成功!-1");
		} else {
			logger.info(orgId + "：该组织下不存在develop！");

			FinanceChannelVo channelVo = new FinanceChannelVo();

			// 获取his实收金额
			FinanceChannelVo realVo = paymentJournalDao.selectSummaryRealHis(orgId, beginCheckTime, endCheckTime,
					payMode, null);
			channelVo.setHis_receive_real_amount(realVo.getHis_receive_real_amount());
			channelVo.setHis_receive_real_pay_count(realVo.getHis_receive_real_pay_count());
			channelVo.setHis_receive_real_pay_amount(realVo.getHis_receive_real_pay_amount());
			channelVo.setHis_receive_real_refund_count(realVo.getHis_receive_real_refund_count());
			channelVo.setHis_receive_real_refund_amount(realVo.getHis_receive_real_refund_amount());

			// 统计：核实金额计算 ~ 支付：核算实收数据 =
			// 应收数据+【上日存疑（院方多）-上日存疑院方多转差错】-【上日存疑（院方少）-上日存疑院方少转差错】-当日存疑（院方多）+当日存疑（院方少）
			FinanceChannelVo costVo = hisOrderDao.selectCosting(orgId, payMode, beginCheckTime, endCheckTime, null);
			channelVo.setHis_receive_pay_count(costVo.getHis_receive_pay_count());
			channelVo.setHis_receive_pay_amount(costVo.getHis_receive_pay_amount());
			channelVo.setHis_pay_refund_count(costVo.getHis_pay_refund_count());
			channelVo.setHis_pay_refund_amount(costVo.getHis_pay_refund_amount());

			channelVo.setPlatform_id(orgId);
			channelVo.setPlatform_name(orgName);

			fcList.add(channelVo);
			response.setResultObject(JsonUtils.toJsonString(fcList));
			response.setResultCodeAndMessage("0", "查询成功!-2");

		}

		return response;
	}

	/**
	 * 按渠道查询对账明细数据
	 *
	 * @param datas
	 * @return
	 * @interfaceName: yyt.pay.finance.detail.by.channel.query
	 */
	@Override
	public ResponseObject queryFinanceDetailByChannel(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);

		String orgId = dataMap.get("org_id");
		String orgName = dataMap.get("org_name");
		String checkTime = dataMap.get("check_time");
		String payMode = dataMap.get("pay_mode");

		List<FinanceDetailVo> fdList = new ArrayList<FinanceDetailVo>();

		checkTime = DateUtils.getDateForType(checkTime, 1);// 日期加一天

		String beginCheckTime = checkTime + " 00:00:00";
		String endCheckTime = checkTime + " 23:59:59";

		// 查询组织下的所有机构
		Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_APP_DEVELOP_LIST,
				JsonUtils.toJsonString(orgId));
		if ("0".equals(baseResp.getResultCode())) {
			List<OrgAppDevelopVo> developVos = JsonUtils.parseArray(baseResp.getResult(), OrgAppDevelopVo.class);
			for (OrgAppDevelopVo developVo : developVos) {

				FinanceDetailVo detailVo = new FinanceDetailVo();



				// 金额差错信息
				FinanceDetailVo todayErrorVo = hisOrderCheckedErrorDao.selectDetailError(orgId, payMode, beginCheckTime,
						endCheckTime, developVo.getPlatformId());
				detailVo.setTday_money_error_pay_count(todayErrorVo.getTday_money_error_pay_count());
				detailVo.setTday_money_error_pay_amount(todayErrorVo.getTday_money_error_pay_amount());
				detailVo.setTday_money_error_refund_count(todayErrorVo.getTday_money_error_refund_count());
				detailVo.setTday_money_error_refund_amount(todayErrorVo.getTday_money_error_refund_amount());

				// 上日存疑院方多转差错
				detailVo.setYday_his_more_problem_to_error_pay_count(
						todayErrorVo.getYday_his_more_problem_to_error_pay_count());
				detailVo.setYday_his_more_problem_to_error_pay_amount(
						todayErrorVo.getYday_his_more_problem_to_error_pay_amount());
				detailVo.setYday_his_more_problem_to_error_refund_count(
						todayErrorVo.getYday_his_more_problem_to_error_refund_count());
				detailVo.setYday_his_more_problem_to_error_refund_amount(
						todayErrorVo.getYday_his_more_problem_to_error_refund_amount());

				// 上日存疑院方少转差错
				detailVo.setYday_his_less_problem_to_error_pay_count(
						todayErrorVo.getYday_his_less_problem_to_error_pay_count());
				detailVo.setYday_his_less_problem_to_error_pay_amount(
						todayErrorVo.getYday_his_less_problem_to_error_pay_amount());
				detailVo.setYday_his_less_problem_to_error_refund_count(
						todayErrorVo.getYday_his_less_problem_to_error_refund_count());
				detailVo.setYday_his_less_problem_to_error_refund_amount(
						todayErrorVo.getYday_his_less_problem_to_error_refund_amount());

				// 上日存疑信息
				FinanceDetailVo doubtVo = hisOrderCheckedDao.selectDetailDoubt(orgId, payMode, beginCheckTime,
						endCheckTime, developVo.getPlatformId());
				detailVo.setYday_his_more_problem_to_equal_pay_count(
						doubtVo.getYday_his_more_problem_to_equal_pay_count());
				detailVo.setYday_his_more_problem_to_equal_pay_amount(
						doubtVo.getYday_his_more_problem_to_equal_pay_amount());
				detailVo.setYday_his_more_problem_to_equal_refund_count(
						doubtVo.getYday_his_more_problem_to_equal_refund_count());
				detailVo.setYday_his_more_problem_to_equal_refund_amount(
						doubtVo.getYday_his_more_problem_to_equal_refund_amount());

				// 上日存疑院方少对平数据
				detailVo.setYday_his_less_problem_to_equal_pay_count(
						doubtVo.getYday_his_less_problem_to_equal_pay_count());
				detailVo.setYday_his_less_problem_to_equal_pay_amount(
						doubtVo.getYday_his_less_problem_to_equal_pay_amount());
				detailVo.setYday_his_less_problem_to_equal_refund_count(
						doubtVo.getYday_his_less_problem_to_equal_refund_count());
				detailVo.setYday_his_less_problem_to_equal_refund_amount(
						doubtVo.getYday_his_less_problem_to_equal_refund_amount());

				// 统计：上日存疑院方多
				detailVo.setYday_his_more_problem_pay_count(
						getSum(detailVo.getYday_his_more_problem_to_equal_pay_count(),
								detailVo.getYday_his_more_problem_to_error_pay_count()));
				detailVo.setYday_his_more_problem_pay_amount(
						getSum(detailVo.getYday_his_more_problem_to_equal_pay_amount(),
								detailVo.getYday_his_more_problem_to_error_pay_amount()));
				detailVo.setYday_his_more_problem_refund_count(
						getSum(detailVo.getYday_his_more_problem_to_equal_refund_count(),
								detailVo.getYday_his_more_problem_to_error_refund_count()));
				detailVo.setYday_his_more_problem_refund_amount(
						getSum(detailVo.getYday_his_more_problem_to_equal_refund_amount(),
								detailVo.getYday_his_more_problem_to_error_refund_amount()));

				// 统计：上日存疑院方少
				detailVo.setYday_his_less_problem_pay_count(
						getSum(detailVo.getYday_his_less_problem_to_equal_pay_count(),
								detailVo.getYday_his_less_problem_to_error_pay_count()));
				detailVo.setYday_his_less_problem_pay_amount(
						getSum(detailVo.getYday_his_less_problem_to_equal_pay_amount(),
								detailVo.getYday_his_less_problem_to_error_pay_amount()));
				detailVo.setYday_his_less_problem_refund_count(
						getSum(detailVo.getYday_his_less_problem_to_equal_refund_count(),
								detailVo.getYday_his_less_problem_to_error_refund_count()));
				detailVo.setYday_his_less_problem_refund_amount(
						getSum(detailVo.getYday_his_less_problem_to_equal_refund_amount(),
								detailVo.getYday_his_less_problem_to_error_refund_amount()));

				detailVo.setPlatform_id(developVo.getPlatformId());
				detailVo.setPlatform_name(developVo.getPlatformName());

				fdList.add(detailVo);
			}

			response.setResultObject(JsonUtils.toJsonString(fdList));
			response.setResultCodeAndMessage("0", "查询成功!-1");

		} else {

			FinanceDetailVo detailVo = new FinanceDetailVo();

			logger.info(orgId + "：该组织下不存在develop！");

			// 获取当日存疑院方信息


			// 金额差错信息
			FinanceDetailVo todayErrorVo = hisOrderCheckedErrorDao.selectDetailError(orgId, payMode, beginCheckTime,
					endCheckTime, null);
			detailVo.setTday_money_error_pay_count(todayErrorVo.getTday_money_error_pay_count());
			detailVo.setTday_money_error_pay_amount(todayErrorVo.getTday_money_error_pay_amount());
			detailVo.setTday_money_error_refund_count(todayErrorVo.getTday_money_error_refund_count());
			detailVo.setTday_money_error_refund_amount(todayErrorVo.getTday_money_error_refund_amount());

			// 上日存疑院方多转差错
			detailVo.setYday_his_more_problem_to_error_pay_count(
					todayErrorVo.getYday_his_more_problem_to_error_pay_count());
			detailVo.setYday_his_more_problem_to_error_pay_amount(
					todayErrorVo.getYday_his_more_problem_to_error_pay_amount());
			detailVo.setYday_his_more_problem_to_error_refund_count(
					todayErrorVo.getYday_his_more_problem_to_error_refund_count());
			detailVo.setYday_his_more_problem_to_error_refund_amount(
					todayErrorVo.getYday_his_more_problem_to_error_refund_amount());

			// 上日存疑院方少转差错
			detailVo.setYday_his_less_problem_to_error_pay_count(
					todayErrorVo.getYday_his_less_problem_to_error_pay_count());
			detailVo.setYday_his_less_problem_to_error_pay_amount(
					todayErrorVo.getYday_his_less_problem_to_error_pay_amount());
			detailVo.setYday_his_less_problem_to_error_refund_count(
					todayErrorVo.getYday_his_less_problem_to_error_refund_count());
			detailVo.setYday_his_less_problem_to_error_refund_amount(
					todayErrorVo.getYday_his_less_problem_to_error_refund_amount());

			// 上日存疑信息
			FinanceDetailVo doubtVo = hisOrderCheckedDao.selectDetailDoubt(orgId, payMode, beginCheckTime, endCheckTime,
					null);
			detailVo.setYday_his_more_problem_to_equal_pay_count(doubtVo.getYday_his_more_problem_to_equal_pay_count());
			detailVo.setYday_his_more_problem_to_equal_pay_amount(
					doubtVo.getYday_his_more_problem_to_equal_pay_amount());
			detailVo.setYday_his_more_problem_to_equal_refund_count(
					doubtVo.getYday_his_more_problem_to_equal_refund_count());
			detailVo.setYday_his_more_problem_to_equal_refund_amount(
					doubtVo.getYday_his_more_problem_to_equal_refund_amount());

			// 上日存疑院方少对平数据
			detailVo.setYday_his_less_problem_to_equal_pay_count(doubtVo.getYday_his_less_problem_to_equal_pay_count());
			detailVo.setYday_his_less_problem_to_equal_pay_amount(
					doubtVo.getYday_his_less_problem_to_equal_pay_amount());
			detailVo.setYday_his_less_problem_to_equal_refund_count(
					doubtVo.getYday_his_less_problem_to_equal_refund_count());
			detailVo.setYday_his_less_problem_to_equal_refund_amount(
					doubtVo.getYday_his_less_problem_to_equal_refund_amount());

			// 统计：上日存疑院方多
			detailVo.setYday_his_more_problem_pay_count(getSum(detailVo.getYday_his_more_problem_to_equal_pay_count(),
					detailVo.getYday_his_more_problem_to_error_pay_count()));
			detailVo.setYday_his_more_problem_pay_amount(getSum(detailVo.getYday_his_more_problem_to_equal_pay_amount(),
					detailVo.getYday_his_more_problem_to_error_pay_amount()));
			detailVo.setYday_his_more_problem_refund_count(
					getSum(detailVo.getYday_his_more_problem_to_equal_refund_count(),
							detailVo.getYday_his_more_problem_to_error_refund_count()));
			detailVo.setYday_his_more_problem_refund_amount(
					getSum(detailVo.getYday_his_more_problem_to_equal_refund_amount(),
							detailVo.getYday_his_more_problem_to_error_refund_amount()));

			// 统计：上日存疑院方少
			detailVo.setYday_his_less_problem_pay_count(getSum(detailVo.getYday_his_less_problem_to_equal_pay_count(),
					detailVo.getYday_his_less_problem_to_error_pay_count()));
			detailVo.setYday_his_less_problem_pay_amount(getSum(detailVo.getYday_his_less_problem_to_equal_pay_amount(),
					detailVo.getYday_his_less_problem_to_error_pay_amount()));
			detailVo.setYday_his_less_problem_refund_count(
					getSum(detailVo.getYday_his_less_problem_to_equal_refund_count(),
							detailVo.getYday_his_less_problem_to_error_refund_count()));
			detailVo.setYday_his_less_problem_refund_amount(
					getSum(detailVo.getYday_his_less_problem_to_equal_refund_amount(),
							detailVo.getYday_his_less_problem_to_error_refund_amount()));

			detailVo.setPlatform_id(orgId);
			detailVo.setPlatform_name(orgName);

			fdList.add(detailVo);

			response.setResultObject(JsonUtils.toJsonString(fdList));
			response.setResultCodeAndMessage("0", "查询成功!-2");
		}

		return response;
	}

	/**
	 * 对账记录查询
	 *
	 * @param datas
	 * @return
	 * @interfaceName: yyt.pay.finance.records.query-old
	 */
	public ResponseObject queryFinanceRecordsOld(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, Object> result = new HashMap<>();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);
		String orgId = dataMap.get("org_id");
		String checkTime = dataMap.get("check_time");
		String payMode = dataMap.get("pay_mode");
		String orderType = dataMap.get("order_type");
		String payStatus = dataMap.get("pay_status");
		String checkStatus = dataMap.get("check_status");
		String yytOrderNo = dataMap.get("yyt_order_no");
		String hisOrderNo = dataMap.get("his_order_no");
		String platform_id = dataMap.get("platform_id");

		String page_num = dataMap.get("page_num");
		String page_size = dataMap.get("page_size");

		PageInfo pageInfo = new PageInfo();

		pageInfo.setPageNum(Integer.valueOf(page_num));
		pageInfo.setPageSize(Integer.valueOf(page_size));

		List<String> checkList = new ArrayList<>();

		checkTime = DateUtils.getDateForType(checkTime, 1);// 日期加一天

		String beginCheckTime = checkTime + " 00:00:00";
		String endCheckTime = checkTime + " 23:59:59";

		if (checkStatus.contains(",")) {
			String[] status = checkStatus.split(",");
			checkList = Arrays.asList(status);
		} else {
			checkList.add(checkStatus);
		}

		if (StringUtils.isBlank(checkStatus)) {
			checkList = null;
		}

		String count = hisOrderCheckedDao.selectRecordsCount(orgId, payMode, orderType, payStatus, checkList,
				yytOrderNo, hisOrderNo, beginCheckTime, endCheckTime, platform_id);

		pageInfo.setTotal(Long.valueOf(count));
		pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());

		List<FinanceRecordsVo> vos = hisOrderCheckedDao.selectRecords(orgId, payMode, orderType, payStatus, checkList,
				yytOrderNo, hisOrderNo, beginCheckTime, endCheckTime, pageInfo, platform_id);

		result.put("list", vos);
		result.put("page_info", pageInfo);

		response.setResultObject(JsonUtils.toJsonString(result));
		response.setResultCodeAndMessage("0", "查询成功!");

		return response;
	}

	/**
	 * 差错处理
	 *
	 * @param datas
	 * @return
	 * @interfacename: yyt.pay.finance.error.record.manage
	 */
	@Override
	public ResponseObject manageFinanceErrorRecord(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);
		String manageStatus = dataMap.get("manage_status");
		String payErrorId = dataMap.get("pay_his_order_checked_error_id");

		HisOrderCheckedError order = hisOrderCheckedErrorDao.selectById(payErrorId);
		if (order != null) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_no", order.getYytOrderNo());
			Response res = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORDER, JSON.toJSONString(map));
			if ("0".equals(res.getResultCode())) {
				OrderExtVo vo = JsonUtils.parseObject(res.getResult(), OrderExtVo.class);
				OrderExceptionVo record = new OrderExceptionVo();
				record.setBranchCode(vo.getBranchCode());
				record.setBranchId(vo.getBranchId());
				record.setBranchName(vo.getBranchName());
				record.setCreatedTime(DateUtils.dateToString(new Date()));
				record.setExceptionHandlerCount(0);
				record.setRefundHandlerCount(0);
				record.setId(PKGenerator.generateId());
				record.setIsInsurance(vo.getIsInsurance());
				record.setOrderNo(vo.getOrderNo());
				record.setOrderType(vo.getOrderType());
				record.setOrgCode(vo.getOrgCode());
				record.setOrgId(vo.getOrgId());
				record.setOrgName(vo.getOrgName());
				record.setPlatformCode(vo.getPlatformCode());
				record.setPlatformId(vo.getPlatformId());
				record.setPlatformName(vo.getPlatformName());
				record.setPlatformOrgAppCode(vo.getPlatformOrgAppCode());
				record.setUpdateTime(DateUtils.dateToString(new Date()));
				record.setHandlerResult((short) 0);
				record.setHisQueryState((short) 0);
				record.setInsuranceHandlerFlag((short) 0);
				record.setSelfPayHandlerFlag((short) 0);

				BaseService.callUnderlineFromInternal("", "yyt.base.order.exception.add", JsonUtils.toJsonString(vo));

				// 查询订单状态更改是否成功
				map = new HashMap<String, String>();
				map.put("order_no", order.getYytOrderNo());
				res = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORDER, JSON.toJSONString(map));
				vo = JsonUtils.parseObject(res.getResult(), OrderExtVo.class);
				if (vo.getPayStatus() == 7) {
					logger.info("订单退费成功！");
					order.setManageStatus(Short.valueOf(manageStatus));
					hisOrderCheckedErrorDao.update(order);
					response.setResultObject(order);
					response.setResultCodeAndMessage("0", "处理成功!");
				} else {
					logger.info("订单退费失败！订单号：" + vo.getOrderNo() + ",订单状态：" + vo.getPayStatus());
					response.setResultCodeAndMessage("5004", "订单退费失败！请联系管理员");
				}
			} else {
				response.setResultCodeAndMessage("5004", "Order查询订单失败!无法处理差错");
				return response;
			}

		} else {
			response.setResultObject(null);
			response.setResultCodeAndMessage("5001", "Error查询订单失败!");
		}

		return response;
	}

	/**
	 * 医院渠道查询
	 *
	 * @param datas
	 * @return
	 * @interfaceName: yyt.pay.finance.hospital.channel.query
	 */
	@Override
	public ResponseObject queryFinanceHospitalChannel(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);
		String orgId = dataMap.get("org_id");
		List<OrgAppDevelopVo> developVos = null;
		// 查询组织下的所有机构
		Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_APP_DEVELOP_LIST,
				JsonUtils.toJsonString(orgId));
		if ("0".equals(baseResp.getResultCode())) {
			developVos = JsonUtils.parseArray(baseResp.getResult(), OrgAppDevelopVo.class);
			response.setResultObject(JsonUtils.toJsonString(developVos));
			response.setResultCodeAndMessage("0", "查询成功！!");

		} else {
			developVos = new ArrayList<OrgAppDevelopVo>();

			// 查询sys_org数据
			Org org = new Org();
			org.setId(orgId);
			Response resop = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORG_BY_ID,
					JsonUtils.toJsonString(orgId));
			if ("0".equals(resop.getResultCode())) {
				org = JsonUtils.parseObject(resop.getResult(), Org.class);
				OrgAppDevelopVo orgAppDevelopVo = new OrgAppDevelopVo();
				orgAppDevelopVo.setOrgId(org.getId());
				orgAppDevelopVo.setOrgName(org.getOrgName());
				orgAppDevelopVo.setPlatformId(org.getId());
				orgAppDevelopVo.setPlatformName(org.getOrgName());

				developVos.add(orgAppDevelopVo);
				response.setResultObject(JsonUtils.toJsonString(developVos));
				response.setResultCodeAndMessage("0", "查询成功!!");
			} else {
				response.setResultObject(null);
				response.setResultCodeAndMessage("5002", "Org数据查询失败!");
			}
		}

		return response;
	}

	/**
	 * 按时间段所有渠道查询对账汇总数据
	 *
	 * @param datas
	 * @return
	 * @interfacename:yyt.pay.finance.summary.timeperiod.query
	 */

	public ResponseObject queryFinanceSummaryTimeperiod2(String datas) {
		ResponseObject response = new ResponseObject();
		Map<String, String> dataMap = JSON.parseObject(datas, Map.class);
		String orgId = dataMap.get("org_id");
		String beginCheckTime = dataMap.get("begin_check_time");
		String endCheckTime = dataMap.get("end_check_time");

		if (StringUtils.isBlank(beginCheckTime) || StringUtils.isBlank(endCheckTime)) {
			response.setResultCodeAndMessage("5003", "对账汇总查询失败！传入时间为null");
			return response;
		}

		Date beginDate = null;
		Date endDate = null;

		try {
			beginDate = YYYYMMDD.parse(beginCheckTime);
			endDate = YYYYMMDD.parse(endCheckTime);
		} catch (ParseException e) {
			logger.error("[FinanceServiceImpl.queryFinanceSummaryTimeperiod]--日期解析异常", e);
		}

		List<FinanceSummaryTimeperiodVo> fstVos = new ArrayList<FinanceSummaryTimeperiodVo>();
		List<Date> dates = DateUtils.getDatesBetweenTwoDate(beginDate, endDate);
		for (Date date : dates) {
			String checkTime = YYYYMMDD.format(date);
			checkTime = DateUtils.getDateForType(checkTime, 1);// 日期加一天
			beginCheckTime = checkTime + " 00:00:00";
			endCheckTime = checkTime + " 23:59:59";
			FinanceSummaryTimeperiodVo timeVo = new FinanceSummaryTimeperiodVo();
			List<FinanceSummaryVo> fsVos = null;
			// 查询组织下的所有机构
			Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_GET_APP_DEVELOP_LIST,
					JsonUtils.toJsonString(orgId));
			if ("0".equals(baseResp.getResultCode())) {
				List<OrgAppDevelopVo> developVos = JsonUtils.parseArray(baseResp.getResult(), OrgAppDevelopVo.class);
				fsVos = new ArrayList<FinanceSummaryVo>();
				for (OrgAppDevelopVo developVo : developVos) {
					FinanceSummaryVo financeSummaryVo = new FinanceSummaryVo();
					FinanceSummaryVo hisVo = paymentSourceFileDao.selectHisReceiveAmount(beginCheckTime, endCheckTime,
							orgId, developVo.getPlatformId());
					financeSummaryVo.setHis_alipay_receive_amount(hisVo.getHis_alipay_receive_amount());
					financeSummaryVo.setHis_wechat_receive_amount(hisVo.getHis_wechat_receive_amount());
					financeSummaryVo.setHis_receive_amount(hisVo.getHis_receive_amount());

					FinanceSummaryVo realVo = paymentSourceFileDao.selectReceiveRealAmount(beginCheckTime, endCheckTime,
							orgId, developVo.getPlatformId());
					financeSummaryVo.setAlipay_receive_real_amount(realVo.getAlipay_receive_real_amount());
					financeSummaryVo.setWechat_receive_real_amount(realVo.getWechat_receive_real_amount());

					financeSummaryVo.setPlatform_id(developVo.getPlatformId());
					financeSummaryVo.setPlatform_name(developVo.getPlatformName());

					fsVos.add(financeSummaryVo);
				}
			} else {
				response.setResultCodeAndMessage("5002", "对账总汇数据查询失败！");
				return response;
			}

			timeVo.setCheck_date(DateUtils.getDateForType(checkTime, 2));
			timeVo.setFinanceSummaryVos(fsVos);
			fstVos.add(timeVo);
		}

		response.setResultObject(fstVos);
		response.setResultCodeAndMessage("0", "查询成功!!");

		return response;
	}

	/**
	 * 对账Excel导出
	 *
	 * @param datas
	 * @return
	 * @interfacename:yyt.pay.finance.excel.download
	 */
	@Override
	public ResponseObject downloadFinanceExcel(String datas) {
		ResponseObject response = new ResponseObject();
		logger.info("downloadFinanceExcel, request data=" + datas);
		FinanceExcelVo request = JsonUtils.parseObject(datas, FinanceExcelVo.class);

		try {
			Validator.getInstance().validate(request);
		} catch (ValidateException ex) {
			logger.info("downloadFinanceExcel 数据校验失败:" + ex.getMessage() + "|入参:" + datas + "！");
			response.setResultCodeAndMessage("13", "数据校验失败:" + ex.getMessage() + "！");
			return response;
		}

		Response resps = new Response();

		// 根据orgId查询orgName
		Response baseResp = BaseService.callHumpFromInternal(MethodRouter.BASE_FIND_ORG_BY_ID,
				JsonUtils.toJsonString(request.getOrgId()));
		if ("0".equals(baseResp.getResultCode())) {
			Org org = JsonUtils.parseObject(baseResp.getResult(), Org.class);
			request.setOrgName(org.getOrgName());
		}

		// 匹配接口名称
		switch (request.getInterfaceName()) {
		case MethodRouter.QUERY_FINANCE_DETAILS_PATSTATISTICS:
			resps = financeExcelService.detailsPatstatisticsExcelTemplate(datas, request);
			break;
		case MethodRouter.QUERY_FINANCE_DETAILS_HISDETAILS:
			resps = financeExcelService.detailsHisdetailsExcelTemplate(datas, request);
			break;
		case MethodRouter.QUERY_FINANCE_DETAILS_PATDETAILS:
			resps = financeExcelService.detailsPatdetailsExcelTemplate(datas, request);
			break;
		case MethodRouter.QUERY_FINANCE_DETAILS_THIRDPAYMENT:
			resps = financeExcelService.detailsThirdpaymentExcelTemplate(datas, request);
			break;
		case MethodRouter.QUERY_FINANCE_SUMMARY_DIFFERENCE:
			resps = financeExcelService.financesDifferenceExcelTemplate(datas, request);
			break;
		case MethodRouter.QUERY_FINANCE_RECORDS:
			resps = financeExcelService.financesRecordsExcelTemplate(datas, request);
			break;
		default:
			response.setResultCodeAndMessage(Response.FAILURE_CODE, Response.FAILURE_MESSAGE);
		}

		// 上传qiniu并提供下载url
		if ("0".equals(resps.getResultCode())) {
			Map<String, String> map = JsonUtils.parseObject(resps.getResult(), Map.class);
			String fileName = map.get("file_name");
			String filePath = map.get("file_path");
			com.qiniu.http.Response upres = QiniuService.upload(filePath, fileName,
					Config.QINIU_BUCKET_FOR_FINANCEEXCEL);
			if (upres.isOK() || upres.statusCode == 614) {
				logger.info("upload Excel file success!");
				String bucketURL = yaml.getProperty(Config.QINIU_FINANCE_EXCEL_DOWNLOAD_URL);
				String path = yaml.getProperty(Config.CONFIG_PAY_ALIPAY_CHECK_ACCOUNT_PATH);

				String url = QiniuService.download(fileName, path, bucketURL);
				if (StringUtils.isBlank(url)) {
					response.setResultCodeAndMessage("2", "Get FinanceBill Excel Url for online is null !");
					return response;
				}

				response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE,
						new FinanceExcel(url));
			} else {
				logger.info("financeExcel_qiniu_upload_fail!!");
				response.setResultCodeAndMessage("2", "失败");
			}
		}

		return response;
	}




	/**
	 * 省二调用his对账统计查询
	 *
	 * @param datas
	 * @return
	 * @interfacename:yyt.pay.finance.collect.query
	 */

	public ResponseObject queryFinanceCollect(String datas) {
		ResponseObject response = new ResponseObject();
		FinanceCollectVo financeCollectVo = JsonUtils.parseObject(datas, FinanceCollectVo.class);

		if(StringUtils.isBlank(financeCollectVo.getHospitalCode())){
			response.setResultCodeAndMessage(Response.FAILURE_CODE , "参数 HospitalCode is null！");
		}

		//查询是否存在统计查询规则
		Map<String, String> map = new HashMap<String, String>();
		map.put("attribute_name", Config.RULE_ATTRIBUTE_NAME_FOR_SHENER_QUERY_COLLECTS);
		map.put("org_code", financeCollectVo.getHospitalCode());
		Response resp = BaseService.callHumpFromInternal(MethodRouter.FIND_SYS_RULE_ATTRIBUTE, JSON.toJSONString(map));
		if(resp.getResult() == null){
			response.setResultCodeAndMessage("52003" , "HospitalCode：" + financeCollectVo.getHospitalCode() + ",未开通对账统计查询功能");
			return response;
		}

		Rule rule = JsonUtils.parseObject(resp.getResult(), Rule.class);
		if("0".equals(rule.getAttributeProperties())){
			response.setResultCodeAndMessage("52004" , "HospitalCode：" + financeCollectVo.getHospitalCode() + ",已开通未启用对账统计查询功能");
			return response;
		}

		logger.info("省二调用his对账统计查询 json:" + JsonUtils.toJsonString(financeCollectVo));
		ResCommon<List<FinanceCollectVoResponse>> financeCollectRespone = HisifaceService.getHisifaceClient().queryFinanceCollect(financeCollectVo);

		if("0".equals(financeCollectRespone.getResultCode())){
			response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(financeCollectRespone.getResult()));
		}else{
			if(financeCollectRespone.getResultMessage().contains("His resultCode:1")){
				response.setResultCodeAndMessageAndResult("52001" , "该日期无数据" , null);
			}else{
				response.setResultCodeAndMessageAndResult("52002" , financeCollectRespone.getResultMessage() , null);
			}
		}

		return response;
	}




	/**
	 * 数据统计
	 *
	 * @return
	 */
	public static String getSum(String num1, String num2) {
		int n1 = Integer.parseInt(num1);
		int n2 = Integer.parseInt(num2);
		return String.valueOf(n1 + n2);
	}

	/*
	 * ============================================以下为提供业务方数据接口=================
	 * ===============================
	 */

	/**
	 * 获取七牛对账文件URL
	 *
	 * @param data
	 * @param sessionId
	 * @return
	 * @interfacename:yyt.pay.finance.bill.ex.url.get
	 */
	public Response getFinanceBillExUrl(String data, String sessionId) {
		Response response = new Response();
		logger.info("getFinanceBillExUrl, request data=" + data + ", sessionId=" + sessionId);
		QiniuFinanceBillRequest request = JsonUtils.parseObject(data, QiniuFinanceBillRequest.class);

		try {
			Validator.getInstance().validate(request);
		} catch (ValidateException ex) {
			logger.info("getFinanceBillExUrl 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
			response.setResultCodeAndMessage("13", "数据校验失败:" + ex.getMessage() + "！");
			return response;
		}

		Map<String, Object> map = new HashMap<String, Object>();

		List<PaymentSettingResponse> paymentSettings = new ArrayList<>();

		map.put("org_id", request.getHospitalCode());
		// 根据orgId获取settlementSetting配置
		ResponseObject resp = paymentService.queryPaymentSettingBySettlementSetting(JSON.toJSONString(map));
		if ("0".equals(resp.getResultCode())) {
			logger.info("Get SettlementSetting Success..");
			List<SettlementSetting> settingVos = (List<SettlementSetting>) resp.getResultObject();
			for (SettlementSetting settingVo : settingVos) {
				ResCommon<PaymentSettingResponse> resCommon = PayService.getPayClient()
						.queryPaymentSettingByAppcodeAndOrgcodeAndPaymode(settingVo.getPlatformOrgAppCode(),
								settingVo.getDevOrgCode(), settingVo.getPayMode());
				if ("0".equals(resCommon.getResultCode())) {
					PaymentSettingResponse paymentSetting = resCommon.getResult();
					logger.info("Get PaymentSetting Success.. --" + paymentSetting.getOrgName() + " APPID："
							+ paymentSetting.getPayAppId());
					paymentSettings.add(paymentSetting);
				}
			}
		} else {
			response.setResultCodeAndMessage("1",
					"Get SettlementSetting error! Please check input orgId --" + request.getHospitalCode());
			return response;
		}

		String payType = "";
		if ("2".equals(request.getType())) {
			payType = "alipay";
		} else if ("1".equals(request.getType())) {
			payType = "wechat";
		}

		String date = request.getGetDate().replace("-", "");

		String bucketURL = yaml.getProperty(Alipay.QINIU_CHECK_ACCTOUNT_DOWNLOAD_URL);
		String path = yaml.getProperty(Config.CONFIG_PAY_ALIPAY_CHECK_ACCOUNT_PATH);

		List<QiniuFinanceBill> bills = new ArrayList<>();

		if (paymentSettings.size() > 0) {
			for (PaymentSettingResponse paymentSetting : paymentSettings) {
				String dowloadUrlName = paymentSetting.getOrgName() + "_" + payType + "_" + date + "_"
						+ paymentSetting.getPayAppId() + ".csv";
				String url = QiniuService.download(dowloadUrlName, path, bucketURL);

				if (StringUtils.isBlank(url)) {
					response.setResultCodeAndMessage("2", "Get FinanceBill Excel Url for online is null !");
					continue;
				}

				QiniuFinanceBill qiniuFinanceBill = new QiniuFinanceBill();
				qiniuFinanceBill.setPayUrlType(String.valueOf(paymentSetting.getPayMode()).substring(0, 1));
				qiniuFinanceBill.setUrl(url);
				bills.add(qiniuFinanceBill);
			}
			response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE,
					JsonUtils.toJsonString(bills));
		} else {
			response.setResultCodeAndMessage("1",
					"PaymentSetting list size problem! Please contact the admin for PaymentSetting --");
			return response;
		}

		return response;
	}

}
